Dataset Viewer
instance_id
stringlengths 12
28
| repo
stringclasses 17
values | patch
stringlengths 0
96.8k
| test_patch
stringlengths 0
9.7k
| problem_statement
stringlengths 95
284k
| run_test
stringlengths 44
591
| base_commit
stringlengths 7
40
| test_file
stringlengths 14
136
|
---|---|---|---|---|---|---|---|
ansible__ansible-4 | ansible/ansible | diff --git a/lib/ansible/playbook/collectionsearch.py b/lib/ansible/playbook/collectionsearch.py
index 93b80a8665..994e2e13e4 100644
--- a/lib/ansible/playbook/collectionsearch.py
+++ b/lib/ansible/playbook/collectionsearch.py
@@ -7,6 +7,10 @@ __metaclass__ = type
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.utils.collection_loader import AnsibleCollectionLoader
+from ansible.template import is_template, Environment
+from ansible.utils.display import Display
+
+display = Display()
def _ensure_default_collection(collection_list=None):
@@ -32,7 +36,8 @@ def _ensure_default_collection(collection_list=None):
class CollectionSearch:
# this needs to be populated before we can resolve tasks/roles/etc
- _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection)
+ _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection,
+ always_post_validate=True, static=True)
def _load_collections(self, attr, ds):
# this will only be called if someone specified a value; call the shared value
@@ -41,4 +46,13 @@ class CollectionSearch:
if not ds: # don't return an empty collection list, just return None
return None
+ # This duplicates static attr checking logic from post_validate()
+ # because if the user attempts to template a collection name, it will
+ # error before it ever gets to the post_validate() warning.
+ env = Environment()
+ for collection_name in ds:
+ if is_template(collection_name, env):
+ display.warning('"collections" is not templatable, but we found: %s, '
+ 'it will not be templated and will be used "as is".' % (collection_name))
+
return ds
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/playbook/test_collectionsearch.py F [100%]
=================================== FAILURES ===================================
________________________ test_collection_static_warning ________________________
capsys = <_pytest.capture.CaptureFixture object at 0x7f3dbe6f8f28>
def test_collection_static_warning(capsys):
"""Test that collection name is not templated.
Also, make sure that users see the warning message for the referenced name.
"""
collection_name = 'foo.{{bar}}'
cs = CollectionSearch()
assert collection_name in cs._load_collections(None, [collection_name])
std_out, std_err = capsys.readouterr()
> assert '[WARNING]: "collections" is not templatable, but we found: %s' % collection_name in std_err
E assert ('[WARNING]: "collections" is not templatable, but we found: %s' % 'foo.{{bar}}') in ''
test/units/playbook/test_collectionsearch.py:37: AssertionError
=========================== 1 failed in 2.39 seconds =========================== | pytest test/units/playbook/test_collectionsearch.py::test_collection_static_warning | d91658ec0c8434c82c3ef98bfe9eb4e1027a43a3 | test/units/playbook/test_collectionsearch.py |
|
ansible__ansible-13 | ansible/ansible | diff --git a/lib/ansible/cli/galaxy.py b/lib/ansible/cli/galaxy.py
index 487f21d0db..9cf3a8e87e 100644
--- a/lib/ansible/cli/galaxy.py
+++ b/lib/ansible/cli/galaxy.py
@@ -29,12 +29,14 @@ from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
+from ansible.module_utils import six
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.playbook.role.requirement import RoleRequirement
from ansible.utils.display import Display
from ansible.utils.plugin_docs import get_versioned_doclink
display = Display()
+urlparse = six.moves.urllib.parse.urlparse
class GalaxyCLI(CLI):
@@ -805,7 +807,13 @@ class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
- name, dummy, requirement = collection_input.partition(':')
+ requirement = None
+ if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
+ urlparse(collection_input).scheme.lower() in ['http', 'https']:
+ # Arg is a file path or URL to a collection
+ name = collection_input
+ else:
+ name, dummy, requirement = collection_input.partition(':')
requirements.append((name, requirement or '*', None))
output_path = GalaxyCLI._resolve_path(output_path)
diff --git a/lib/ansible/galaxy/collection.py b/lib/ansible/galaxy/collection.py
index 0569605a3d..ede9492251 100644
--- a/lib/ansible/galaxy/collection.py
+++ b/lib/ansible/galaxy/collection.py
@@ -827,9 +827,13 @@ def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
- elif urlparse(collection).scheme:
+ elif urlparse(collection).scheme.lower() in ['http', 'https']:
display.vvvv("Collection requirement '%s' is a URL to a tar artifact" % collection)
- b_tar_path = _download_file(collection, b_temp_path, None, validate_certs)
+ try:
+ b_tar_path = _download_file(collection, b_temp_path, None, validate_certs)
+ except urllib_error.URLError as err:
+ raise AnsibleError("Failed to download collection tar from '%s': %s"
+ % (to_native(collection), to_native(err)))
if b_tar_path:
req = CollectionRequirement.from_tar(b_tar_path, force, parent=parent)
| diff --git a/test/units/cli/test_galaxy.py b/test/units/cli/test_galaxy.py
index bc6628d2b3..f8b544e09f 100644
--- a/test/units/cli/test_galaxy.py
+++ b/test/units/cli/test_galaxy.py
@@ -890,6 +890,29 @@ def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
+def test_collection_install_with_url(collection_install):
+ mock_install, dummy, output_dir = collection_install
+
+ galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',
+ '--collections-path', output_dir]
+ GalaxyCLI(args=galaxy_args).run()
+
+ collection_path = os.path.join(output_dir, 'ansible_collections')
+ assert os.path.isdir(collection_path)
+
+ assert mock_install.call_count == 1
+ assert mock_install.call_args[0][0] == [('https://foo/bar/foo-bar-v1.0.0.tar.gz', '*', None)]
+ assert mock_install.call_args[0][1] == collection_path
+ assert len(mock_install.call_args[0][2]) == 1
+ assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
+ assert mock_install.call_args[0][2][0].validate_certs is True
+ assert mock_install.call_args[0][3] is True
+ assert mock_install.call_args[0][4] is False
+ assert mock_install.call_args[0][5] is False
+ assert mock_install.call_args[0][6] is False
+ assert mock_install.call_args[0][7] is False
+
+
def test_collection_install_name_and_requirements_fail(collection_install):
test_path = collection_install[2]
expected = 'The positional collection_name arg and --requirements-file are mutually exclusive.'
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/cli/test_galaxy.py F [100%]
=================================== FAILURES ===================================
_______________________ test_collection_install_with_url _______________________
collection_install = (<MagicMock id='140127118734952'>, <MagicMock id='140127118744768'>, '/tmp/pytest-of-root/pytest-4/test-ÅÑŚÌβŁÈ Output0')
def test_collection_install_with_url(collection_install):
mock_install, dummy, output_dir = collection_install
galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',
'--collections-path', output_dir]
GalaxyCLI(args=galaxy_args).run()
collection_path = os.path.join(output_dir, 'ansible_collections')
assert os.path.isdir(collection_path)
assert mock_install.call_count == 1
> assert mock_install.call_args[0][0] == [('https://foo/bar/foo-bar-v1.0.0.tar.gz', '*', None)]
E AssertionError: assert [('https', '/...ar.gz', None)] == [('https://foo...', '*', None)]
E At index 0 diff: ('https', '//foo/bar/foo-bar-v1.0.0.tar.gz', None) != ('https://foo/bar/foo-bar-v1.0.0.tar.gz', '*', None)
E Use -v to get the full diff
test/units/cli/test_galaxy.py:904: AssertionError
=========================== 1 failed in 0.69 seconds =========================== | pytest test/units/cli/test_galaxy.py::test_collection_install_with_url | 41472ee3878be215af8b933b2b04b4a72b9165ca | test/units/cli/test_galaxy.py |
ansible__ansible-9 | ansible/ansible | diff --git a/lib/ansible/modules/packaging/os/redhat_subscription.py b/lib/ansible/modules/packaging/os/redhat_subscription.py
index bc0bcc3ee7..d3cca7beb0 100644
--- a/lib/ansible/modules/packaging/os/redhat_subscription.py
+++ b/lib/ansible/modules/packaging/os/redhat_subscription.py
@@ -515,7 +515,9 @@ class Rhsm(RegistrationBase):
for pool_id, quantity in sorted(pool_ids.items()):
if pool_id in available_pool_ids:
- args = [SUBMAN_CMD, 'attach', '--pool', pool_id, '--quantity', quantity]
+ args = [SUBMAN_CMD, 'attach', '--pool', pool_id]
+ if quantity is not None:
+ args.extend(['--quantity', to_native(quantity)])
rc, stderr, stdout = self.module.run_command(args, check_rc=True)
else:
self.module.fail_json(msg='Pool ID: %s not in list of available pools' % pool_id)
@@ -839,8 +841,8 @@ def main():
module.fail_json(msg='Unable to parse pool_ids option.')
pool_id, quantity = list(value.items())[0]
else:
- pool_id, quantity = value, 1
- pool_ids[pool_id] = str(quantity)
+ pool_id, quantity = value, None
+ pool_ids[pool_id] = quantity
consumer_type = module.params["consumer_type"]
consumer_name = module.params["consumer_name"]
consumer_id = module.params["consumer_id"]
| diff --git a/test/units/modules/packaging/os/test_redhat_subscription.py b/test/units/modules/packaging/os/test_redhat_subscription.py
index 50c714b1e7..b2a11894fa 100644
--- a/test/units/modules/packaging/os/test_redhat_subscription.py
+++ b/test/units/modules/packaging/os/test_redhat_subscription.py
@@ -557,8 +557,7 @@ Entitlement Type: Physical
[
'/testbin/subscription-manager',
'attach',
- '--pool', 'ff8080816b8e967f016b8e99632804a6',
- '--quantity', '1'
+ '--pool', 'ff8080816b8e967f016b8e99632804a6'
],
{'check_rc': True},
(0, '', '')
@@ -567,8 +566,7 @@ Entitlement Type: Physical
[
'/testbin/subscription-manager',
'attach',
- '--pool', 'ff8080816b8e967f016b8e99747107e9',
- '--quantity', '1'
+ '--pool', 'ff8080816b8e967f016b8e99747107e9'
],
{'check_rc': True},
(0, '', '')
@@ -658,7 +656,6 @@ Entitlement Type: Physical
'/testbin/subscription-manager',
'attach',
'--pool', 'ff8080816b8e967f016b8e99632804a6',
- '--quantity', '1'
],
{'check_rc': True},
(0, '', '')
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 13 items
test/units/modules/packaging/os/test_redhat_subscription.py ..........FF [ 92%]
. [100%]
=================================== FAILURES ===================================
___ test_redhat_subscribtion[test_registeration_username_password_pool_ids] ____
mocker = <pytest_mock.MockFixture object at 0x7f040d2567f0>
capfd = <_pytest.capture.CaptureFixture object at 0x7f040d2532b0>
patch_redhat_subscription = None
testcase = {'changed': True, 'id': 'test_registeration_username_password_pool_ids', 'msg': "System successfully registered to 'No...tbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9'], {'check_rc': True}, (0, '', ''))]}
@pytest.mark.parametrize('patch_ansible_module, testcase', TEST_CASES, ids=TEST_CASES_IDS, indirect=['patch_ansible_module'])
@pytest.mark.usefixtures('patch_ansible_module')
def test_redhat_subscribtion(mocker, capfd, patch_redhat_subscription, testcase):
"""
Run unit tests for test cases listen in TEST_CASES
"""
# Mock function used for running commands first
call_results = [item[2] for item in testcase['run_command.calls']]
mock_run_command = mocker.patch.object(
basic.AnsibleModule,
'run_command',
side_effect=call_results)
# Try to run test case
with pytest.raises(SystemExit):
redhat_subscription.main()
out, err = capfd.readouterr()
results = json.loads(out)
assert 'changed' in results
assert results['changed'] == testcase['changed']
if 'msg' in results:
assert results['msg'] == testcase['msg']
assert basic.AnsibleModule.run_command.call_count == len(testcase['run_command.calls'])
if basic.AnsibleModule.run_command.call_count:
call_args_list = [(item[0][0], item[1]) for item in basic.AnsibleModule.run_command.call_args_list]
expected_call_args_list = [(item[0], item[1]) for item in testcase['run_command.calls']]
> assert call_args_list == expected_call_args_list
E AssertionError: assert [(['/testbin/...k_rc': True})] == [(['/testbin/s...k_rc': True})]
E At index 3 diff: (['/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1'], {'check_rc': True}) != (['/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6'], {'check_rc': True})
E Use -v to get the full diff
test/units/modules/packaging/os/test_redhat_subscription.py:848: AssertionError
__ test_redhat_subscribtion[test_registeration_username_password_one_pool_id] __
mocker = <pytest_mock.MockFixture object at 0x7f040d339f98>
capfd = <_pytest.capture.CaptureFixture object at 0x7f040d339550>
patch_redhat_subscription = None
testcase = {'changed': True, 'id': 'test_registeration_username_password_one_pool_id', 'msg': "System successfully registered to ...tbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6'], {'check_rc': True}, (0, '', ''))]}
@pytest.mark.parametrize('patch_ansible_module, testcase', TEST_CASES, ids=TEST_CASES_IDS, indirect=['patch_ansible_module'])
@pytest.mark.usefixtures('patch_ansible_module')
def test_redhat_subscribtion(mocker, capfd, patch_redhat_subscription, testcase):
"""
Run unit tests for test cases listen in TEST_CASES
"""
# Mock function used for running commands first
call_results = [item[2] for item in testcase['run_command.calls']]
mock_run_command = mocker.patch.object(
basic.AnsibleModule,
'run_command',
side_effect=call_results)
# Try to run test case
with pytest.raises(SystemExit):
redhat_subscription.main()
out, err = capfd.readouterr()
results = json.loads(out)
assert 'changed' in results
assert results['changed'] == testcase['changed']
if 'msg' in results:
assert results['msg'] == testcase['msg']
assert basic.AnsibleModule.run_command.call_count == len(testcase['run_command.calls'])
if basic.AnsibleModule.run_command.call_count:
call_args_list = [(item[0][0], item[1]) for item in basic.AnsibleModule.run_command.call_args_list]
expected_call_args_list = [(item[0], item[1]) for item in testcase['run_command.calls']]
> assert call_args_list == expected_call_args_list
E AssertionError: assert [(['/testbin/...k_rc': True})] == [(['/testbin/s...k_rc': True})]
E At index 3 diff: (['/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1'], {'check_rc': True}) != (['/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6'], {'check_rc': True})
E Use -v to get the full diff
test/units/modules/packaging/os/test_redhat_subscription.py:848: AssertionError
===================== 2 failed, 11 passed in 0.12 seconds ====================== | pytest test/units/modules/packaging/os/test_redhat_subscription.py::test_redhat_subscribtion | 9276dd2007a73172ed99ab5a56cded4298d3cd2b | test/units/modules/packaging/os/test_redhat_subscription.py |
ansible__ansible-7 | ansible/ansible | diff --git a/lib/ansible/module_utils/network/eos/config/vlans/vlans.py b/lib/ansible/module_utils/network/eos/config/vlans/vlans.py
index 99cb37cd07..c2a701637d 100644
--- a/lib/ansible/module_utils/network/eos/config/vlans/vlans.py
+++ b/lib/ansible/module_utils/network/eos/config/vlans/vlans.py
@@ -208,16 +208,17 @@ def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
+ for key in to_remove:
+ if key in to_set.keys():
+ continue
+ commands.append("no {0}".format(key))
+
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
- for key in to_remove:
- commands.append("no {0}".format(key))
-
if commands:
commands.insert(0, "vlan {0}".format(vlan_id))
-
return commands
| diff --git a/test/units/modules/network/eos/test_eos_vlans.py b/test/units/modules/network/eos/test_eos_vlans.py
index 5bdc878305..63f4d38d14 100644
--- a/test/units/modules/network/eos/test_eos_vlans.py
+++ b/test/units/modules/network/eos/test_eos_vlans.py
@@ -102,12 +102,12 @@ class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
- vlan_id=30,
- name="thirty",
+ vlan_id=10,
+ name="tenreplaced",
state="suspend"
)], state="replaced"
))
- commands = ['vlan 30', 'name thirty', 'state suspend']
+ commands = ['vlan 10', 'name tenreplaced', 'state suspend']
self.execute_module(changed=True, commands=commands)
def test_eos_vlan_replaced_idempotent(self):
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/modules/network/eos/test_eos_vlans.py F [100%]
=================================== FAILURES ===================================
__________________ TestEosVlansModule.test_eos_vlan_replaced ___________________
self = <units.modules.network.eos.test_eos_vlans.TestEosVlansModule testMethod=test_eos_vlan_replaced>
def test_eos_vlan_replaced(self):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=10,
name="tenreplaced",
state="suspend"
)], state="replaced"
))
commands = ['vlan 10', 'name tenreplaced', 'state suspend']
> self.execute_module(changed=True, commands=commands)
test/units/modules/network/eos/test_eos_vlans.py:111:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
test/units/modules/network/eos/eos_module.py:79: in execute_module
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
E AssertionError: Lists differ: ['name tenreplaced', 'state suspend', 'vlan 10'] != ['name tenreplaced', 'no name', 'state suspend', 'vlan 10']
E
E First differing element 1:
E 'state suspend'
E 'no name'
E
E Second list contains 1 additional elements.
E First extra element 3:
E 'vlan 10'
E
E - ['name tenreplaced', 'state suspend', 'vlan 10']
E + ['name tenreplaced', 'no name', 'state suspend', 'vlan 10']
E ? +++++++++++
E : ['vlan 10', 'name tenreplaced', 'state suspend', 'no name']
=========================== 1 failed in 0.13 seconds =========================== | pytest test/units/modules/network/eos/test_eos_vlans.py::TestEosVlansModule::test_eos_vlan_replaced | cd146b836e032df785ecd9eb711c6ef23c2228b8 | test/units/modules/network/eos/test_eos_vlans.py |
ansible__ansible-12 | ansible/ansible | diff --git a/lib/ansible/plugins/lookup/env.py b/lib/ansible/plugins/lookup/env.py
index 6892feb8c5..5926bfeea4 100644
--- a/lib/ansible/plugins/lookup/env.py
+++ b/lib/ansible/plugins/lookup/env.py
@@ -27,9 +27,8 @@ RETURN = """
- values from the environment variables.
type: list
"""
-import os
-
from ansible.plugins.lookup import LookupBase
+from ansible.utils import py3compat
class LookupModule(LookupBase):
@@ -39,6 +38,6 @@ class LookupModule(LookupBase):
ret = []
for term in terms:
var = term.split()[0]
- ret.append(os.getenv(var, ''))
+ ret.append(py3compat.environ.get(var, ''))
return ret
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 4 items
test/units/plugins/lookup/test_env.py FFFF [100%]
=================================== FAILURES ===================================
_________________________ test_env_var_value[foo-bar] __________________________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f40a2566278>
env_var = 'foo', exp_value = 'bar'
@pytest.mark.parametrize('env_var,exp_value', [
('foo', 'bar'),
('equation', 'a=b*100')
])
def test_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
> assert retval == [exp_value]
E AssertionError: assert [''] == ['bar']
E At index 0 diff: '' != 'bar'
E Use -v to get the full diff
test/units/plugins/lookup/test_env.py:23: AssertionError
_____________________ test_env_var_value[equation-a=b*100] _____________________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f40a256eba8>
env_var = 'equation', exp_value = 'a=b*100'
@pytest.mark.parametrize('env_var,exp_value', [
('foo', 'bar'),
('equation', 'a=b*100')
])
def test_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
> assert retval == [exp_value]
E AssertionError: assert [''] == ['a=b*100']
E At index 0 diff: '' != 'a=b*100'
E Use -v to get the full diff
test/units/plugins/lookup/test_env.py:23: AssertionError
____________ test_utf8_env_var_value[simple_var-alpha-\u03b2-gamma] ____________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f40a2568d30>
env_var = 'simple_var', exp_value = 'alpha-β-gamma'
@pytest.mark.parametrize('env_var,exp_value', [
('simple_var', 'alpha-β-gamma'),
('the_var', 'ãnˈsiβle')
])
def test_utf8_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
> assert retval == [exp_value]
E AssertionError: assert [''] == ['alpha-β-gamma']
E At index 0 diff: '' != 'alpha-β-gamma'
E Use -v to get the full diff
test/units/plugins/lookup/test_env.py:35: AssertionError
____________ test_utf8_env_var_value[the_var-\xe3n\u02c8si\u03b2le] ____________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f40a256e7f0>
env_var = 'the_var', exp_value = 'ãnˈsiβle'
@pytest.mark.parametrize('env_var,exp_value', [
('simple_var', 'alpha-β-gamma'),
('the_var', 'ãnˈsiβle')
])
def test_utf8_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
> assert retval == [exp_value]
E AssertionError: assert [''] == ['ãnˈsiβle']
E At index 0 diff: '' != 'ãnˈsiβle'
E Use -v to get the full diff
test/units/plugins/lookup/test_env.py:35: AssertionError
=========================== 4 failed in 0.69 seconds =========================== | pytest test/units/plugins/lookup/test_env.py | 05e2e1806162393d76542a75c2520c7d61c2d855 | test/units/plugins/lookup/test_env.py |
|
ansible__ansible-6 | ansible/ansible | diff --git a/lib/ansible/galaxy/collection.py b/lib/ansible/galaxy/collection.py
index 24b13d97a1..4d7b327613 100644
--- a/lib/ansible/galaxy/collection.py
+++ b/lib/ansible/galaxy/collection.py
@@ -219,12 +219,15 @@ class CollectionRequirement:
requirement = req
op = operator.eq
- # In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
- # version as '*' (unknown version) unless the requirement is also '*'.
- if parent and version == '*' and requirement != '*':
- break
- elif requirement == '*' or version == '*':
- continue
+ # In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
+ # version as '*' (unknown version) unless the requirement is also '*'.
+ if parent and version == '*' and requirement != '*':
+ display.warning("Failed to validate the collection requirement '%s:%s' for %s when the existing "
+ "install does not have a version set, the collection may not work."
+ % (to_text(self), req, parent))
+ continue
+ elif requirement == '*' or version == '*':
+ continue
if not op(LooseVersion(version), LooseVersion(requirement)):
break
@@ -286,7 +289,13 @@ class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
- version = manifest['version']
+ version = to_text(manifest['version'], errors='surrogate_or_strict')
+
+ if not hasattr(LooseVersion(version), 'version'):
+ display.warning("Collection at '%s' does not have a valid version set, falling back to '*'. Found "
+ "version: '%s'" % (to_text(b_path), version))
+ version = '*'
+
dependencies = manifest['dependencies']
else:
display.warning("Collection at '%s' does not have a MANIFEST.json file, cannot detect version."
@@ -877,7 +886,7 @@ def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
- existing[0].add_requirement(to_text(collection_info), requirement)
+ existing[0].add_requirement(parent, requirement)
collection_info = existing[0]
dep_map[to_text(collection_info)] = collection_info
| diff --git a/test/units/galaxy/test_collection_install.py b/test/units/galaxy/test_collection_install.py
index 3efd833b18..fc437db681 100644
--- a/test/units/galaxy/test_collection_install.py
+++ b/test/units/galaxy/test_collection_install.py
@@ -165,13 +165,14 @@ def test_build_requirement_from_path(collection_artifact):
assert actual.dependencies == {}
-def test_build_requirement_from_path_with_manifest(collection_artifact):
+@pytest.mark.parametrize('version', ['1.1.1', 1.1, 1])
+def test_build_requirement_from_path_with_manifest(version, collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
'namespace': 'namespace',
'name': 'name',
- 'version': '1.1.1',
+ 'version': version,
'dependencies': {
'ansible_namespace.collection': '*'
}
@@ -188,8 +189,8 @@ def test_build_requirement_from_path_with_manifest(collection_artifact):
assert actual.b_path == collection_artifact[0]
assert actual.api is None
assert actual.skip is True
- assert actual.versions == set([u'1.1.1'])
- assert actual.latest_version == u'1.1.1'
+ assert actual.versions == set([to_text(version)])
+ assert actual.latest_version == to_text(version)
assert actual.dependencies == {'ansible_namespace.collection': '*'}
@@ -203,6 +204,42 @@ def test_build_requirement_from_path_invalid_manifest(collection_artifact):
collection.CollectionRequirement.from_path(collection_artifact[0], True)
+def test_build_requirement_from_path_no_version(collection_artifact, monkeypatch):
+ manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
+ manifest_value = json.dumps({
+ 'collection_info': {
+ 'namespace': 'namespace',
+ 'name': 'name',
+ 'version': '',
+ 'dependencies': {}
+ }
+ })
+ with open(manifest_path, 'wb') as manifest_obj:
+ manifest_obj.write(to_bytes(manifest_value))
+
+ mock_display = MagicMock()
+ monkeypatch.setattr(Display, 'display', mock_display)
+
+ actual = collection.CollectionRequirement.from_path(collection_artifact[0], True)
+
+ # While the folder name suggests a different collection, we treat MANIFEST.json as the source of truth.
+ assert actual.namespace == u'namespace'
+ assert actual.name == u'name'
+ assert actual.b_path == collection_artifact[0]
+ assert actual.api is None
+ assert actual.skip is True
+ assert actual.versions == set(['*'])
+ assert actual.latest_version == u'*'
+ assert actual.dependencies == {}
+
+ assert mock_display.call_count == 1
+
+ actual_warn = ' '.join(mock_display.mock_calls[0][1][0].split('\n'))
+ expected_warn = "Collection at '%s' does not have a valid version set, falling back to '*'. Found version: ''" \
+ % to_text(collection_artifact[0])
+ assert expected_warn in actual_warn
+
+
def test_build_requirement_from_tar(collection_artifact):
actual = collection.CollectionRequirement.from_tar(collection_artifact[1], True, True)
@@ -497,13 +534,20 @@ def test_add_collection_requirements(versions, requirement, expected_filter, exp
assert req.latest_version == expected_latest
-def test_add_collection_requirement_to_unknown_installed_version():
+def test_add_collection_requirement_to_unknown_installed_version(monkeypatch):
+ mock_display = MagicMock()
+ monkeypatch.setattr(Display, 'display', mock_display)
+
req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,
skip=True)
- expected = "Cannot meet requirement namespace.name:1.0.0 as it is already installed at version 'unknown'."
- with pytest.raises(AnsibleError, match=expected):
- req.add_requirement(str(req), '1.0.0')
+ req.add_requirement('parent.collection', '1.0.0')
+ assert req.latest_version == '*'
+
+ assert mock_display.call_count == 1
+
+ actual_warn = ' '.join(mock_display.mock_calls[0][1][0].split('\n'))
+ assert "Failed to validate the collection requirement 'namespace.name:1.0.0' for parent.collection" in actual_warn
def test_add_collection_wildcard_requirement_to_unknown_installed_version():
| RUN EVERY COMMAND
0
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 3 items
test/units/galaxy/test_collection_install.py .FF [100%]
=================================== FAILURES ===================================
_____________ test_build_requirement_from_path_with_manifest[1.1] ______________
version = 1.1
collection_artifact = (b'/tmp/pytest-of-root/pytest-8/test-\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input1/ansib...\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input1/ansible_namespace-collection-0.1.0.tar.gz')
@pytest.mark.parametrize('version', ['1.1.1', 1.1, 1])
def test_build_requirement_from_path_with_manifest(version, collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
'namespace': 'namespace',
'name': 'name',
'version': version,
'dependencies': {
'ansible_namespace.collection': '*'
}
}
})
with open(manifest_path, 'wb') as manifest_obj:
manifest_obj.write(to_bytes(manifest_value))
> actual = collection.CollectionRequirement.from_path(collection_artifact[0], True)
test/units/galaxy/test_collection_install.py:184:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:305: in from_path
metadata=meta, files=files, skip=True)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:88: in __init__
self.add_requirement(parent, requirement)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in add_requirement
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in <genexpr>
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <ansible.galaxy.collection.CollectionRequirement object at 0x7f51d9bc2160>
version = 1.1, requirements = 1.1, parent = None
def _meets_requirements(self, version, requirements, parent):
"""
Supports version identifiers can be '==', '!=', '>', '>=', '<', '<=', '*'. Each requirement is delimited by ','
"""
op_map = {
'!=': operator.ne,
'==': operator.eq,
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
}
> for req in list(requirements.split(',')):
E AttributeError: 'float' object has no attribute 'split'
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:213: AttributeError
---------------------------- Captured stdout setup -----------------------------
- Collection ansible_namespace.collection was created successfully
Created collection for ansible_namespace.collection at /tmp/pytest-of-root/pytest-8/test-ÅÑŚÌβŁÈ Collections Input1/ansible_namespace-collection-0.1.0.tar.gz
______________ test_build_requirement_from_path_with_manifest[1] _______________
version = 1
collection_artifact = (b'/tmp/pytest-of-root/pytest-8/test-\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input2/ansib...\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input2/ansible_namespace-collection-0.1.0.tar.gz')
@pytest.mark.parametrize('version', ['1.1.1', 1.1, 1])
def test_build_requirement_from_path_with_manifest(version, collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
'namespace': 'namespace',
'name': 'name',
'version': version,
'dependencies': {
'ansible_namespace.collection': '*'
}
}
})
with open(manifest_path, 'wb') as manifest_obj:
manifest_obj.write(to_bytes(manifest_value))
> actual = collection.CollectionRequirement.from_path(collection_artifact[0], True)
test/units/galaxy/test_collection_install.py:184:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:305: in from_path
metadata=meta, files=files, skip=True)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:88: in __init__
self.add_requirement(parent, requirement)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in add_requirement
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in <genexpr>
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <ansible.galaxy.collection.CollectionRequirement object at 0x7f51d9b17ac8>
version = 1, requirements = 1, parent = None
def _meets_requirements(self, version, requirements, parent):
"""
Supports version identifiers can be '==', '!=', '>', '>=', '<', '<=', '*'. Each requirement is delimited by ','
"""
op_map = {
'!=': operator.ne,
'==': operator.eq,
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
}
> for req in list(requirements.split(',')):
E AttributeError: 'int' object has no attribute 'split'
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:213: AttributeError
---------------------------- Captured stdout setup -----------------------------
- Collection ansible_namespace.collection was created successfully
Created collection for ansible_namespace.collection at /tmp/pytest-of-root/pytest-8/test-ÅÑŚÌβŁÈ Collections Input2/ansible_namespace-collection-0.1.0.tar.gz
====================== 2 failed, 1 passed in 0.89 seconds ======================
RUN EVERY COMMAND
1
pytest test/units/galaxy/test_collection_install.py::test_build_requirement_from_path_with_manifest
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/galaxy/test_collection_install.py F [100%]
=================================== FAILURES ===================================
_________________ test_build_requirement_from_path_no_version __________________
collection_artifact = (b'/tmp/pytest-of-root/pytest-9/test-\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input0/ansib...\xc3\x85\xc3\x91\xc5\x9a\xc3\x8c\xce\xb2\xc5\x81\xc3\x88 Collections Input0/ansible_namespace-collection-0.1.0.tar.gz')
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7ff7a6a3a1d0>
def test_build_requirement_from_path_no_version(collection_artifact, monkeypatch):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
'namespace': 'namespace',
'name': 'name',
'version': '',
'dependencies': {}
}
})
with open(manifest_path, 'wb') as manifest_obj:
manifest_obj.write(to_bytes(manifest_value))
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
> actual = collection.CollectionRequirement.from_path(collection_artifact[0], True)
test/units/galaxy/test_collection_install.py:223:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:305: in from_path
metadata=meta, files=files, skip=True)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:88: in __init__
self.add_requirement(parent, requirement)
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in add_requirement
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:120: in <genexpr>
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:229: in _meets_requirements
if not op(LooseVersion(version), LooseVersion(requirement)):
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/distutils/version.py:46: in __eq__
c = self._cmp(other)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <[AttributeError("'LooseVersion' object has no attribute 'vstring'") raised in repr()] LooseVersion object at 0x7ff7a6a2b6a0>
other = <[AttributeError("'LooseVersion' object has no attribute 'vstring'") raised in repr()] LooseVersion object at 0x7ff7a6a2b630>
def _cmp (self, other):
if isinstance(other, str):
other = LooseVersion(other)
> if self.version == other.version:
E AttributeError: 'LooseVersion' object has no attribute 'version'
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/distutils/version.py:335: AttributeError
---------------------------- Captured stdout setup -----------------------------
- Collection ansible_namespace.collection was created successfully
Created collection for ansible_namespace.collection at /tmp/pytest-of-root/pytest-9/test-ÅÑŚÌβŁÈ Collections Input0/ansible_namespace-collection-0.1.0.tar.gz
=========================== 1 failed in 0.68 seconds ===========================
RUN EVERY COMMAND
2
pytest test/units/galaxy/test_collection_install.py::test_build_requirement_from_path_no_version
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/galaxy/test_collection_install.py F [100%]
=================================== FAILURES ===================================
_________ test_add_collection_requirement_to_unknown_installed_version _________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7fe570865e48>
def test_add_collection_requirement_to_unknown_installed_version(monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,
skip=True)
> req.add_requirement('parent.collection', '1.0.0')
test/units/galaxy/test_collection_install.py:544:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <ansible.galaxy.collection.CollectionRequirement object at 0x7fe5708765f8>
parent = 'parent.collection', requirement = '1.0.0'
def add_requirement(self, parent, requirement):
self.required_by.append((parent, requirement))
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
if len(new_versions) == 0:
if self.skip:
force_flag = '--force-with-deps' if parent else '--force'
version = self.latest_version if self.latest_version != '*' else 'unknown'
msg = "Cannot meet requirement %s:%s as it is already installed at version '%s'. Use %s to overwrite" \
% (to_text(self), requirement, version, force_flag)
> raise AnsibleError(msg)
E ansible.errors.AnsibleError: Cannot meet requirement namespace.name:1.0.0 as it is already installed at version 'unknown'. Use --force-with-deps to overwrite
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:127: AnsibleError
=========================== 1 failed in 0.58 seconds =========================== | pytest test/units/galaxy/test_collection_install.py::test_build_requirement_from_path_with_manifest
pytest test/units/galaxy/test_collection_install.py::test_build_requirement_from_path_no_version
pytest test/units/galaxy/test_collection_install.py::test_add_collection_requirement_to_unknown_installed_version | 90898132e456ee1993db99a1531379f1b98ee915 | test/units/galaxy/test_collection_install.py |
ansible__ansible-2 | ansible/ansible | diff --git a/lib/ansible/utils/version.py b/lib/ansible/utils/version.py
index 0dc6687ed9..d69723b473 100644
--- a/lib/ansible/utils/version.py
+++ b/lib/ansible/utils/version.py
@@ -72,14 +72,14 @@ class _Alpha:
raise ValueError
- def __gt__(self, other):
- return not self.__lt__(other)
-
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
+ def __gt__(self, other):
+ return not self.__le__(other)
+
def __ge__(self, other):
- return self.__gt__(other) or self.__eq__(other)
+ return not self.__lt__(other)
class _Numeric:
@@ -115,14 +115,14 @@ class _Numeric:
raise ValueError
- def __gt__(self, other):
- return not self.__lt__(other)
-
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
+ def __gt__(self, other):
+ return not self.__le__(other)
+
def __ge__(self, other):
- return self.__gt__(other) or self.__eq__(other)
+ return not self.__lt__(other)
class SemanticVersion(Version):
| diff --git a/test/units/utils/test_version.py b/test/units/utils/test_version.py
index a46282876f..7d04c112c5 100644
--- a/test/units/utils/test_version.py
+++ b/test/units/utils/test_version.py
@@ -268,6 +268,31 @@ def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
+ # The following 3*6 tests check that all comparison operators perform
+ # as expected. DO NOT remove any of them, or reformulate them (to remove
+ # the explicit `not`)!
+
+ assert _Alpha('a') == _Alpha('a')
+ assert not _Alpha('a') != _Alpha('a') # pylint: disable=unneeded-not
+ assert not _Alpha('a') < _Alpha('a') # pylint: disable=unneeded-not
+ assert _Alpha('a') <= _Alpha('a')
+ assert not _Alpha('a') > _Alpha('a') # pylint: disable=unneeded-not
+ assert _Alpha('a') >= _Alpha('a')
+
+ assert not _Alpha('a') == _Alpha('b') # pylint: disable=unneeded-not
+ assert _Alpha('a') != _Alpha('b')
+ assert _Alpha('a') < _Alpha('b')
+ assert _Alpha('a') <= _Alpha('b')
+ assert not _Alpha('a') > _Alpha('b') # pylint: disable=unneeded-not
+ assert not _Alpha('a') >= _Alpha('b') # pylint: disable=unneeded-not
+
+ assert not _Alpha('b') == _Alpha('a') # pylint: disable=unneeded-not
+ assert _Alpha('b') != _Alpha('a')
+ assert not _Alpha('b') < _Alpha('a') # pylint: disable=unneeded-not
+ assert not _Alpha('b') <= _Alpha('a') # pylint: disable=unneeded-not
+ assert _Alpha('b') > _Alpha('a')
+ assert _Alpha('b') >= _Alpha('a')
+
def test_numeric():
assert _Numeric(1) == _Numeric(1)
@@ -283,3 +308,28 @@ def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2)
+
+ # The following 3*6 tests check that all comparison operators perform
+ # as expected. DO NOT remove any of them, or reformulate them (to remove
+ # the explicit `not`)!
+
+ assert _Numeric(1) == _Numeric(1)
+ assert not _Numeric(1) != _Numeric(1) # pylint: disable=unneeded-not
+ assert not _Numeric(1) < _Numeric(1) # pylint: disable=unneeded-not
+ assert _Numeric(1) <= _Numeric(1)
+ assert not _Numeric(1) > _Numeric(1) # pylint: disable=unneeded-not
+ assert _Numeric(1) >= _Numeric(1)
+
+ assert not _Numeric(1) == _Numeric(2) # pylint: disable=unneeded-not
+ assert _Numeric(1) != _Numeric(2)
+ assert _Numeric(1) < _Numeric(2)
+ assert _Numeric(1) <= _Numeric(2)
+ assert not _Numeric(1) > _Numeric(2) # pylint: disable=unneeded-not
+ assert not _Numeric(1) >= _Numeric(2) # pylint: disable=unneeded-not
+
+ assert not _Numeric(2) == _Numeric(1) # pylint: disable=unneeded-not
+ assert _Numeric(2) != _Numeric(1)
+ assert not _Numeric(2) < _Numeric(1) # pylint: disable=unneeded-not
+ assert not _Numeric(2) <= _Numeric(1) # pylint: disable=unneeded-not
+ assert _Numeric(2) > _Numeric(1)
+ assert _Numeric(2) >= _Numeric(1)
| 0
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/utils/test_version.py F [100%]
=================================== FAILURES ===================================
__________________________________ test_alpha __________________________________
def test_alpha():
assert _Alpha('a') == _Alpha('a')
assert _Alpha('a') == 'a'
assert _Alpha('a') != _Alpha('b')
assert _Alpha('a') != 1
assert _Alpha('a') < _Alpha('b')
assert _Alpha('a') < 'c'
assert _Alpha('a') > _Numeric(1)
with pytest.raises(ValueError):
_Alpha('a') < None
assert _Alpha('a') <= _Alpha('a')
assert _Alpha('a') <= _Alpha('b')
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
assert _Alpha('a') == _Alpha('a')
assert not _Alpha('a') != _Alpha('a') # pylint: disable=unneeded-not
assert not _Alpha('a') < _Alpha('a') # pylint: disable=unneeded-not
assert _Alpha('a') <= _Alpha('a')
> assert not _Alpha('a') > _Alpha('a') # pylint: disable=unneeded-not
E AssertionError: assert not 'a' > 'a'
E + where 'a' = _Alpha('a')
E + and 'a' = _Alpha('a')
test/units/utils/test_version.py:279: AssertionError
=========================== 1 failed in 0.36 seconds ===========================
RUN EVERY COMMAND
1
pytest test/units/utils/test_version.py::test_alpha
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/utils/test_version.py F [100%]
=================================== FAILURES ===================================
_________________________________ test_numeric _________________________________
def test_numeric():
assert _Numeric(1) == _Numeric(1)
assert _Numeric(1) == 1
assert _Numeric(1) != _Numeric(2)
assert _Numeric(1) != 'a'
assert _Numeric(1) < _Numeric(2)
assert _Numeric(1) < 3
assert _Numeric(1) < _Alpha('b')
with pytest.raises(ValueError):
_Numeric(1) < None
assert _Numeric(1) <= _Numeric(1)
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2)
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
assert _Numeric(1) == _Numeric(1)
assert not _Numeric(1) != _Numeric(1) # pylint: disable=unneeded-not
assert not _Numeric(1) < _Numeric(1) # pylint: disable=unneeded-not
assert _Numeric(1) <= _Numeric(1)
> assert not _Numeric(1) > _Numeric(1) # pylint: disable=unneeded-not
E assert not 1 > 1
E + where 1 = _Numeric(1)
E + and 1 = _Numeric(1)
test/units/utils/test_version.py:320: AssertionError
=========================== 1 failed in 0.13 seconds =========================== | pytest test/units/utils/test_version.py::test_alpha
pytest test/units/utils/test_version.py::test_numeric | de59b17c7f69d5cfb72479b71776cc8b97e29a6b | test/units/utils/test_version.py |
ansible__ansible-3 | ansible/ansible | diff --git a/lib/ansible/module_utils/facts/system/distribution.py b/lib/ansible/module_utils/facts/system/distribution.py
index 606dbc19bd..528b0e2b9e 100644
--- a/lib/ansible/module_utils/facts/system/distribution.py
+++ b/lib/ansible/module_utils/facts/system/distribution.py
@@ -320,7 +320,8 @@ class DistributionFiles:
elif 'SteamOS' in data:
debian_facts['distribution'] = 'SteamOS'
# nothing else to do, SteamOS gets correct info from python functions
- elif path == '/etc/lsb-release' and 'Kali' in data:
+ elif path in ('/etc/lsb-release', '/etc/os-release') and 'Kali' in data:
+ # Kali does not provide /etc/lsb-release anymore
debian_facts['distribution'] = 'Kali'
release = re.search('DISTRIB_RELEASE=(.*)', data)
if release:
| diff --git a/test/units/module_utils/test_distribution_version.py b/test/units/module_utils/test_distribution_version.py
index c92e3a4024..c709b76a53 100644
--- a/test/units/module_utils/test_distribution_version.py
+++ b/test/units/module_utils/test_distribution_version.py
@@ -990,6 +990,40 @@ TESTSETS = [
'os_family': 'Debian'
}
},
+ {
+ 'name': 'Kali 2020.2',
+ 'input': {
+ '/etc/os-release': ("PRETTY_NAME=\"Kali GNU/Linux Rolling\"\nNAME=\"Kali GNU/Linux\"\nID=kali\nVERSION=\"2020.2\"\n"
+ "VERSION_ID=\"2020.2\"\nVERSION_CODENAME=\"kali-rolling\"\nID_LIKE=debian\nANSI_COLOR=\"1;31\"\n"
+ "HOME_URL=\"https://www.kali.org/\"\nSUPPORT_URL=\"https://forums.kali.org/\"\n"
+ "BUG_REPORT_URL=\"https://bugs.kali.org/\""),
+ '/usr/lib/os-release': ("PRETTY_NAME=\"Kali GNU/Linux Rolling\"\nNAME=\"Kali GNU/Linux\"\nID=kali\nVERSION=\"2020.2\"\n"
+ "VERSION_ID=\"2020.2\"\nVERSION_CODENAME=\"kali-rolling\"\nID_LIKE=debian\nANSI_COLOR=\"1;31\"\n"
+ "HOME_URL=\"https://www.kali.org/\"\nSUPPORT_URL=\"https://forums.kali.org/\"\n"
+ "BUG_REPORT_URL=\"https://bugs.kali.org/\"")
+ },
+ 'platform.dist': [
+ 'kali',
+ '2020.2',
+ ''
+ ],
+ 'distro': {
+ 'codename': 'kali-rolling',
+ 'id': 'kali',
+ 'name': 'Kali GNU/Linux Rolling',
+ 'version': '2020.2',
+ 'version_best': '2020.2',
+ 'os_release_info': {},
+ 'lsb_release_info': {},
+ },
+ 'result': {
+ 'distribution': 'Kali',
+ 'distribution_version': '2020.2',
+ 'distribution_release': 'kali-rolling',
+ 'distribution_major_version': '2020',
+ 'os_family': 'Debian'
+ }
+ },
{
"platform.dist": [
"neon",
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 54 items
test/units/module_utils/test_distribution_version.py ................... [ 35%]
..........F........................ [100%]
=================================== FAILURES ===================================
________________ test_distribution_version[stdin29-Kali 2020.2] ________________
am = <ansible.module_utils.basic.AnsibleModule object at 0x7fd48ca13978>
mocker = <pytest_mock.MockFixture object at 0x7fd48cba85f8>
testcase = {'distro': {'codename': 'kali-rolling', 'id': 'kali', 'lsb_release_info': {}, 'name': 'Kali GNU/Linux Rolling', ...}, ....org/"\nBUG_REPORT_URL="https://bugs.kali.org/"'}, 'name': 'Kali 2020.2', 'platform.dist': ['kali', '2020.2', ''], ...}
@pytest.mark.parametrize("stdin, testcase", product([{}], TESTSETS), ids=lambda x: x.get('name'), indirect=['stdin'])
def test_distribution_version(am, mocker, testcase):
"""tests the distribution parsing code of the Facts class
testsets have
* a name (for output/debugging only)
* input files that are faked
* those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
* all files that are not listed here are assumed to not exist at all
* the output of ansible.module_utils.distro.linux_distribution() [called platform.dist() for historical reasons]
* results for the ansible variables distribution* and os_family
"""
# prepare some mock functions to get the testdata in
def mock_get_file_content(fname, default=None, strip=True):
"""give fake content if it exists, otherwise pretend the file is empty"""
data = default
if fname in testcase['input']:
# for debugging
print('faked %s for %s' % (fname, testcase['name']))
data = testcase['input'][fname].strip()
if strip and data is not None:
data = data.strip()
return data
def mock_get_uname(am, flags):
if '-v' in flags:
return testcase.get('uname_v', None)
elif '-r' in flags:
return testcase.get('uname_r', None)
else:
return None
def mock_file_exists(fname, allow_empty=False):
if fname not in testcase['input']:
return False
if allow_empty:
return True
return bool(len(testcase['input'][fname]))
def mock_platform_system():
return testcase.get('platform.system', 'Linux')
def mock_platform_release():
return testcase.get('platform.release', '')
def mock_platform_version():
return testcase.get('platform.version', '')
def mock_distro_name():
return testcase['distro']['name']
def mock_distro_id():
return testcase['distro']['id']
def mock_distro_version(best=False):
if best:
return testcase['distro']['version_best']
return testcase['distro']['version']
def mock_distro_codename():
return testcase['distro']['codename']
def mock_distro_os_release_info():
return testcase['distro']['os_release_info']
def mock_distro_lsb_release_info():
return testcase['distro']['lsb_release_info']
def mock_open(filename, mode='r'):
if filename in testcase['input']:
file_object = mocker.mock_open(read_data=testcase['input'][filename]).return_value
file_object.__iter__.return_value = testcase['input'][filename].splitlines(True)
else:
file_object = real_open(filename, mode)
return file_object
def mock_os_path_is_file(filename):
if filename in testcase['input']:
return True
return False
mocker.patch('ansible.module_utils.facts.system.distribution.get_file_content', mock_get_file_content)
mocker.patch('ansible.module_utils.facts.system.distribution.get_uname', mock_get_uname)
mocker.patch('ansible.module_utils.facts.system.distribution._file_exists', mock_file_exists)
mocker.patch('ansible.module_utils.distro.name', mock_distro_name)
mocker.patch('ansible.module_utils.distro.id', mock_distro_id)
mocker.patch('ansible.module_utils.distro.version', mock_distro_version)
mocker.patch('ansible.module_utils.distro.codename', mock_distro_codename)
mocker.patch(
'ansible.module_utils.common.sys_info.distro.os_release_info',
mock_distro_os_release_info)
mocker.patch(
'ansible.module_utils.common.sys_info.distro.lsb_release_info',
mock_distro_lsb_release_info)
mocker.patch('os.path.isfile', mock_os_path_is_file)
mocker.patch('platform.system', mock_platform_system)
mocker.patch('platform.release', mock_platform_release)
mocker.patch('platform.version', mock_platform_version)
real_open = builtins.open
mocker.patch.object(builtins, 'open', new=mock_open)
# run Facts()
distro_collector = DistributionFactCollector()
generated_facts = distro_collector.collect(am)
# compare with the expected output
# testcase['result'] has a list of variables and values it expects Facts() to set
for key, val in testcase['result'].items():
assert key in generated_facts
msg = 'Comparing value of %s on %s, should: %s, is: %s' %\
(key, testcase['name'], val, generated_facts[key])
> assert generated_facts[key] == val, msg
E AssertionError: Comparing value of distribution on Kali 2020.2, should: Kali, is: Kali GNU/Linux
E assert 'Kali GNU/Linux' == 'Kali'
E - Kali GNU/Linux
E + Kali
test/units/module_utils/test_distribution_version.py:1965: AssertionError
----------------------------- Captured stdout call -----------------------------
faked /etc/os-release for Kali 2020.2
faked /etc/os-release for Kali 2020.2
faked /etc/os-release for Kali 2020.2
faked /usr/lib/os-release for Kali 2020.2
faked /etc/os-release for Kali 2020.2
===================== 1 failed, 53 passed in 0.88 seconds ====================== | pytest test/units/module_utils/test_distribution_version.py::test_distribution_version | 70219df9056ffb1e2766f572fbe71f7a1800c9f5 | test/units/module_utils/test_distribution_version.py |
ansible__ansible-10 | ansible/ansible | diff --git a/lib/ansible/modules/system/pamd.py b/lib/ansible/modules/system/pamd.py
index 0d8e32b5ae..50da1fcf9e 100644
--- a/lib/ansible/modules/system/pamd.py
+++ b/lib/ansible/modules/system/pamd.py
@@ -351,6 +351,8 @@ class PamdRule(PamdLine):
valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset']
def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
+ self.prev = None
+ self.next = None
self._control = None
self._args = None
self.rule_type = rule_type
@@ -478,7 +480,8 @@ class PamdService(object):
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
- current_line.next.prev = current_line.prev
+ if current_line.next is not None:
+ current_line.next.prev = current_line.prev
else:
self._head = current_line.next
current_line.next.prev = None
| diff --git a/test/units/modules/system/test_pamd.py b/test/units/modules/system/test_pamd.py
index 35d4cb1c3a..93c1d08ad4 100644
--- a/test/units/modules/system/test_pamd.py
+++ b/test/units/modules/system/test_pamd.py
@@ -134,6 +134,12 @@ session required pam_unix.so"""
auth required pam_env.so
"""
+ self.no_header_system_auth_string = """auth required pam_env.so
+auth sufficient pam_unix.so nullok try_first_pass
+auth requisite pam_succeed_if.so uid
+auth required pam_deny.so
+"""
+
self.pamd = PamdService(self.system_auth_string)
def test_properly_parsed(self):
@@ -353,3 +359,14 @@ session required pam_unix.so"""
self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so'))
test_rule = PamdRule('account', 'required', 'pam_unix.so')
self.assertNotIn(str(test_rule), str(self.pamd))
+
+ def test_remove_first_rule(self):
+ no_header_service = PamdService(self.no_header_system_auth_string)
+ self.assertTrue(no_header_service.remove('auth', 'required', 'pam_env.so'))
+ test_rule = PamdRule('auth', 'required', 'pam_env.so')
+ self.assertNotIn(str(test_rule), str(no_header_service))
+
+ def test_remove_last_rule(self):
+ self.assertTrue(self.pamd.remove('session', 'required', 'pam_unix.so'))
+ test_rule = PamdRule('session', 'required', 'pam_unix.so')
+ self.assertNotIn(str(test_rule), str(self.pamd))
| 0
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/modules/system/test_pamd.py F [100%]
=================================== FAILURES ===================================
__________________ PamdServiceTestCase.test_remove_first_rule __________________
self = <units.modules.system.test_pamd.PamdServiceTestCase testMethod=test_remove_first_rule>
def test_remove_first_rule(self):
no_header_service = PamdService(self.no_header_system_auth_string)
> self.assertTrue(no_header_service.remove('auth', 'required', 'pam_env.so'))
test/units/modules/system/test_pamd.py:365:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <ansible.modules.system.pamd.PamdService object at 0x7f3ac2b83358>
rule_type = 'auth', rule_control = 'required', rule_path = 'pam_env.so'
def remove(self, rule_type, rule_control, rule_path):
current_line = self._head
changed = 0
while current_line is not None:
if current_line.matches(rule_type, rule_control, rule_path):
> if current_line.prev is not None:
E AttributeError: 'PamdRule' object has no attribute 'prev'
/opt/conda/envs/e91cde33ffcafb3e40ee0f44cab38afc/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/modules/system/pamd.py:479: AttributeError
=========================== 1 failed in 0.11 seconds ===========================
RUN EVERY COMMAND
1
pytest test/units/modules/system/test_pamd.py::PamdServiceTestCase::test_remove_first_rule
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/modules/system/test_pamd.py F [100%]
=================================== FAILURES ===================================
__________________ PamdServiceTestCase.test_remove_last_rule ___________________
self = <units.modules.system.test_pamd.PamdServiceTestCase testMethod=test_remove_last_rule>
def test_remove_last_rule(self):
> self.assertTrue(self.pamd.remove('session', 'required', 'pam_unix.so'))
test/units/modules/system/test_pamd.py:370:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <ansible.modules.system.pamd.PamdService object at 0x7f5a76a36208>
rule_type = 'session', rule_control = 'required', rule_path = 'pam_unix.so'
def remove(self, rule_type, rule_control, rule_path):
current_line = self._head
changed = 0
while current_line is not None:
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
> current_line.next.prev = current_line.prev
E AttributeError: 'NoneType' object has no attribute 'prev'
/opt/conda/envs/e91cde33ffcafb3e40ee0f44cab38afc/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/modules/system/pamd.py:481: AttributeError
=========================== 1 failed in 0.05 seconds =========================== | pytest test/units/modules/system/test_pamd.py::PamdServiceTestCase::test_remove_first_rule
pytest test/units/modules/system/test_pamd.py::PamdServiceTestCase::test_remove_last_rule | e368f788f71c338cd3f049d5d6bdc643a51c0514 | test/units/modules/system/test_pamd.py |
ansible__ansible-8 | ansible/ansible | diff --git a/lib/ansible/plugins/shell/powershell.py b/lib/ansible/plugins/shell/powershell.py
index ee23147cc5..ca2d5ebf5b 100644
--- a/lib/ansible/plugins/shell/powershell.py
+++ b/lib/ansible/plugins/shell/powershell.py
@@ -22,6 +22,7 @@ import re
import shlex
import pkgutil
import xml.etree.ElementTree as ET
+import ntpath
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_text
@@ -93,14 +94,13 @@ class ShellModule(ShellBase):
return ""
def join_path(self, *args):
- parts = []
- for arg in args:
- arg = self._unquote(arg).replace('/', '\\')
- parts.extend([a for a in arg.split('\\') if a])
- path = '\\'.join(parts)
- if path.startswith('~'):
- return path
- return path
+ # use normpath() to remove doubled slashed and convert forward to backslashes
+ parts = [ntpath.normpath(self._unquote(arg)) for arg in args]
+
+ # Becuase ntpath.join treats any component that begins with a backslash as an absolute path,
+ # we have to strip slashes from at least the beginning, otherwise join will ignore all previous
+ # path components except for the drive.
+ return ntpath.join(parts[0], *[part.strip('\\') for part in parts[1:]])
def get_remote_filename(self, pathname):
# powershell requires that script files end with .ps1
| diff --git a/test/units/plugins/shell/test_powershell.py b/test/units/plugins/shell/test_powershell.py
index a73070c689..6da7ffd5e6 100644
--- a/test/units/plugins/shell/test_powershell.py
+++ b/test/units/plugins/shell/test_powershell.py
@@ -1,4 +1,4 @@
-from ansible.plugins.shell.powershell import _parse_clixml
+from ansible.plugins.shell.powershell import _parse_clixml, ShellModule
def test_parse_clixml_empty():
@@ -51,3 +51,11 @@ def test_parse_clixml_multiple_streams():
expected = b"hi info"
actual = _parse_clixml(multiple_stream, stream="Info")
assert actual == expected
+
+
+def test_join_path_unc():
+ pwsh = ShellModule()
+ unc_path_parts = ['\\\\host\\share\\dir1\\\\dir2\\', '\\dir3/dir4', 'dir5', 'dir6\\']
+ expected = '\\\\host\\share\\dir1\\dir2\\dir3\\dir4\\dir5\\dir6'
+ actual = pwsh.join_path(*unc_path_parts)
+ assert actual == expected
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/plugins/shell/test_powershell.py F [100%]
=================================== FAILURES ===================================
______________________________ test_join_path_unc ______________________________
def test_join_path_unc():
pwsh = ShellModule()
unc_path_parts = ['\\\\host\\share\\dir1\\\\dir2\\', '\\dir3/dir4', 'dir5', 'dir6\\']
expected = '\\\\host\\share\\dir1\\dir2\\dir3\\dir4\\dir5\\dir6'
actual = pwsh.join_path(*unc_path_parts)
> assert actual == expected
E AssertionError: assert 'host\\share\...4\\dir5\\dir6' == '\\\\host\\sha...4\\dir5\\dir6'
E - host\share\dir1\dir2\dir3\dir4\dir5\dir6
E + \\host\share\dir1\dir2\dir3\dir4\dir5\dir6
E ? ++
test/units/plugins/shell/test_powershell.py:61: AssertionError
=========================== 1 failed in 0.56 seconds =========================== | pytest test/units/plugins/shell/test_powershell.py::test_join_path_unc | 81378b3e744cd0d13b33d18a4f8a38aeb8a6e97a | test/units/plugins/shell/test_powershell.py |
ansible__ansible-17 | ansible/ansible | diff --git a/lib/ansible/module_utils/facts/hardware/linux.py b/lib/ansible/module_utils/facts/hardware/linux.py
index 19ca6e4799..befc2fb5e7 100644
--- a/lib/ansible/module_utils/facts/hardware/linux.py
+++ b/lib/ansible/module_utils/facts/hardware/linux.py
@@ -79,6 +79,9 @@ class LinuxHardware(Hardware):
# regex used against mtab content to find entries that are bind mounts
MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"')
+ # regex used for replacing octal escape sequences
+ OCTAL_ESCAPE_RE = re.compile(r'\\[0-9]{3}')
+
def populate(self, collected_facts=None):
hardware_facts = {}
self.module.run_command_environ_update = {'LANG': 'C', 'LC_ALL': 'C', 'LC_NUMERIC': 'C'}
@@ -460,6 +463,14 @@ class LinuxHardware(Hardware):
mtab_entries.append(fields)
return mtab_entries
+ @staticmethod
+ def _replace_octal_escapes_helper(match):
+ # Convert to integer using base8 and then convert to character
+ return chr(int(match.group()[1:], 8))
+
+ def _replace_octal_escapes(self, value):
+ return self.OCTAL_ESCAPE_RE.sub(self._replace_octal_escapes_helper, value)
+
def get_mount_info(self, mount, device, uuids):
mount_size = get_mount_size(mount)
@@ -485,6 +496,8 @@ class LinuxHardware(Hardware):
pool = ThreadPool(processes=min(len(mtab_entries), cpu_count()))
maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT
for fields in mtab_entries:
+ # Transform octal escape sequences
+ fields = [self._replace_octal_escapes(field) for field in fields]
device, mount, fstype, options = fields[0], fields[1], fields[2], fields[3]
| diff --git a/test/units/module_utils/facts/test_facts.py b/test/units/module_utils/facts/test_facts.py
index a037ee0ce3..ae1678341c 100644
--- a/test/units/module_utils/facts/test_facts.py
+++ b/test/units/module_utils/facts/test_facts.py
@@ -514,7 +514,11 @@ MTAB_ENTRIES = [
'0',
'0'
],
- ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0']]
+ ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0'],
+ # Mount path with space in the name
+ # The space is encoded as \040 since the fields in /etc/mtab are space-delimeted
+ ['/dev/sdz9', r'/mnt/foo\040bar', 'ext4', 'rw,relatime', '0', '0'],
+]
BIND_MOUNTS = ['/not/a/real/bind_mount']
@@ -555,6 +559,11 @@ class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase):
self.assertIsInstance(mount_facts['mounts'], list)
self.assertIsInstance(mount_facts['mounts'][0], dict)
+ # Find mounts with space in the mountpoint path
+ mounts_with_space = [x for x in mount_facts['mounts'] if ' ' in x['mount']]
+ self.assertEqual(len(mounts_with_space), 1)
+ self.assertEqual(mounts_with_space[0]['mount'], '/mnt/foo bar')
+
@patch('ansible.module_utils.facts.hardware.linux.get_file_content', return_value=MTAB)
def test_get_mtab_entries(self, mock_get_file_content):
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/module_utils/facts/test_facts.py F [100%]
=================================== FAILURES ===================================
___________ TestFactsLinuxHardwareGetMountFacts.test_get_mount_facts ___________
self = <units.module_utils.facts.test_facts.TestFactsLinuxHardwareGetMountFacts testMethod=test_get_mount_facts>
mock_lsblk_uuid = <MagicMock name='_udevadm_uuid' id='140585510347328'>
mock_find_bind_mounts = <MagicMock name='_lsblk_uuid' id='140585510347440'>
mock_mtab_entries = <MagicMock name='_find_bind_mounts' id='140585510388344'>
mock_udevadm_uuid = <MagicMock name='_mtab_entries' id='140585510346936'>
@patch('ansible.module_utils.facts.hardware.linux.LinuxHardware._mtab_entries', return_value=MTAB_ENTRIES)
@patch('ansible.module_utils.facts.hardware.linux.LinuxHardware._find_bind_mounts', return_value=BIND_MOUNTS)
@patch('ansible.module_utils.facts.hardware.linux.LinuxHardware._lsblk_uuid', return_value=LSBLK_UUIDS)
@patch('ansible.module_utils.facts.hardware.linux.LinuxHardware._udevadm_uuid', return_value=UDEVADM_UUID)
def test_get_mount_facts(self,
mock_lsblk_uuid,
mock_find_bind_mounts,
mock_mtab_entries,
mock_udevadm_uuid):
module = Mock()
# Returns a LinuxHardware-ish
lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
# Nothing returned, just self.facts modified as a side effect
mount_facts = lh.get_mount_facts()
self.assertIsInstance(mount_facts, dict)
self.assertIn('mounts', mount_facts)
self.assertIsInstance(mount_facts['mounts'], list)
self.assertIsInstance(mount_facts['mounts'][0], dict)
# Find mounts with space in the mountpoint path
mounts_with_space = [x for x in mount_facts['mounts'] if ' ' in x['mount']]
> self.assertEqual(len(mounts_with_space), 1)
E AssertionError: 0 != 1
test/units/module_utils/facts/test_facts.py:564: AssertionError
=========================== 1 failed in 0.53 seconds =========================== | pytest test/units/module_utils/facts/test_facts.py::TestFactsLinuxHardwareGetMountFacts::test_get_mount_facts | 9cb47832d15c61884b30d70f9d4e0f816b064b05 | test/units/module_utils/facts/test_facts.py |
ansible__ansible-15 | ansible/ansible | diff --git a/lib/ansible/modules/network/eos/eos_eapi.py b/lib/ansible/modules/network/eos/eos_eapi.py
index 07eeaf93eb..d3825a30df 100644
--- a/lib/ansible/modules/network/eos/eos_eapi.py
+++ b/lib/ansible/modules/network/eos/eos_eapi.py
@@ -264,7 +264,7 @@ def map_obj_to_commands(updates, module, warnings):
else:
add('protocol unix-socket')
- if needs_update('state') and not needs_update('vrf'):
+ if needs_update('state'):
if want['state'] == 'stopped':
add('shutdown')
elif want['state'] == 'started':
| diff --git a/test/units/modules/network/eos/test_eos_eapi.py b/test/units/modules/network/eos/test_eos_eapi.py
index 3d80f19bd3..f002689e0c 100644
--- a/test/units/modules/network/eos/test_eos_eapi.py
+++ b/test/units/modules/network/eos/test_eos_eapi.py
@@ -134,7 +134,7 @@ class TestEosEapiModule(TestEosModule):
def test_eos_eapi_vrf(self):
set_module_args(dict(vrf='test'))
- commands = ['management api http-commands', 'vrf test', 'no shutdown']
+ commands = ['management api http-commands', 'no shutdown', 'vrf test', 'no shutdown']
self.start_unconfigured(changed=True, commands=commands)
def test_eos_eapi_change_from_default_vrf(self):
@@ -142,6 +142,10 @@ class TestEosEapiModule(TestEosModule):
commands = ['management api http-commands', 'vrf test', 'no shutdown']
self.start_configured(changed=True, commands=commands)
+ def test_eos_eapi_default(self):
+ set_module_args(dict())
+ self.start_configured(changed=False, commands=[])
+
def test_eos_eapi_vrf_missing(self):
set_module_args(dict(vrf='missing'))
self.start_unconfigured(failed=True)
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/modules/network/eos/test_eos_eapi.py F [100%]
=================================== FAILURES ===================================
_____________________ TestEosEapiModule.test_eos_eapi_vrf ______________________
self = <units.modules.network.eos.test_eos_eapi.TestEosEapiModule testMethod=test_eos_eapi_vrf>
def test_eos_eapi_vrf(self):
set_module_args(dict(vrf='test'))
commands = ['management api http-commands', 'no shutdown', 'vrf test', 'no shutdown']
> self.start_unconfigured(changed=True, commands=commands)
test/units/modules/network/eos/test_eos_eapi.py:138:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
test/units/modules/network/eos/test_eos_eapi.py:81: in start_unconfigured
return self.execute_module(*args, **kwargs)
test/units/modules/network/eos/eos_module.py:79: in execute_module
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
E AssertionError: Lists differ: ['management api http-commands', 'no shutdown', 'no shutdown', 'vrf test'] != ['management api http-commands', 'no shutdown', 'vrf test']
E
E First differing element 2:
E 'no shutdown'
E 'vrf test'
E
E First list contains 1 additional elements.
E First extra element 3:
E 'vrf test'
E
E - ['management api http-commands', 'no shutdown', 'no shutdown', 'vrf test']
E ? ---------------
E
E + ['management api http-commands', 'no shutdown', 'vrf test'] : ['management api http-commands', 'vrf test', 'no shutdown']
=========================== 1 failed in 0.30 seconds =========================== | pytest test/units/modules/network/eos/test_eos_eapi.py::TestEosEapiModule::test_eos_eapi_vrf | b1e8a6c1cbd2a668b462995487b819ef7dd8ba4b | test/units/modules/network/eos/test_eos_eapi.py |
ansible__ansible-11 | ansible/ansible | diff --git a/lib/ansible/modules/network/ios/ios_banner.py b/lib/ansible/modules/network/ios/ios_banner.py
index be85781058..c28838407c 100644
--- a/lib/ansible/modules/network/ios/ios_banner.py
+++ b/lib/ansible/modules/network/ios/ios_banner.py
@@ -89,10 +89,9 @@ commands:
- string
"""
from ansible.module_utils.basic import AnsibleModule
-from ansible.module_utils.connection import exec_command
-from ansible.module_utils.network.ios.ios import load_config
+from ansible.module_utils.network.ios.ios import get_config, load_config
from ansible.module_utils.network.ios.ios import ios_argument_spec
-import re
+from re import search, M
def map_obj_to_commands(updates, module):
@@ -107,7 +106,7 @@ def map_obj_to_commands(updates, module):
if want['text'] and (want['text'] != have.get('text')):
banner_cmd = 'banner %s' % module.params['banner']
banner_cmd += ' @\n'
- banner_cmd += want['text'].strip()
+ banner_cmd += want['text'].strip('\n')
banner_cmd += '\n@'
commands.append(banner_cmd)
@@ -115,17 +114,21 @@ def map_obj_to_commands(updates, module):
def map_config_to_obj(module):
- rc, out, err = exec_command(module, 'show banner %s' % module.params['banner'])
- if rc == 0:
- output = out
- else:
- rc, out, err = exec_command(module,
- 'show running-config | begin banner %s'
- % module.params['banner'])
- if out:
- output = re.search(r'\^C(.*?)\^C', out, re.S).group(1).strip()
+ """
+ This function gets the banner config without stripping any whitespaces,
+ and then fetches the required banner from it.
+ :param module:
+ :return: banner config dict object.
+ """
+ out = get_config(module, flags='| begin banner %s' % module.params['banner'])
+ if out:
+ regex = 'banner ' + module.params['banner'] + ' ^C\n'
+ if search('banner ' + module.params['banner'], out, M):
+ output = str((out.split(regex))[1].split("^C\n")[0])
else:
output = None
+ else:
+ output = None
obj = {'banner': module.params['banner'], 'state': 'absent'}
if output:
obj['text'] = output
@@ -135,9 +138,6 @@ def map_config_to_obj(module):
def map_params_to_obj(module):
text = module.params['text']
- if text:
- text = str(text).strip()
-
return {
'banner': module.params['banner'],
'text': text,
| diff --git a/test/units/modules/network/ios/test_ios_banner.py b/test/units/modules/network/ios/test_ios_banner.py
index 4e7106e966..cdd43d8e79 100644
--- a/test/units/modules/network/ios/test_ios_banner.py
+++ b/test/units/modules/network/ios/test_ios_banner.py
@@ -30,20 +30,21 @@ class TestIosBannerModule(TestIosModule):
def setUp(self):
super(TestIosBannerModule, self).setUp()
- self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command')
- self.exec_command = self.mock_exec_command.start()
+ self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config')
+ self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.ios.ios_banner.load_config')
self.load_config = self.mock_load_config.start()
def tearDown(self):
super(TestIosBannerModule, self).tearDown()
- self.mock_exec_command.stop()
+ self.mock_get_config.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None):
- self.exec_command.return_value = (0, load_fixture('ios_banner_show_banner.txt').strip(), None)
- self.load_config.return_value = dict(diff=None, session='session')
+ def load_from_file(*args, **kwargs):
+ return load_fixture('ios_banner_show_running_config_ios12.txt')
+ self.get_config.side_effect = load_from_file
def test_ios_banner_create(self):
for banner_type in ('login', 'motd', 'exec', 'incoming', 'slip-ppp'):
@@ -57,21 +58,19 @@ class TestIosBannerModule(TestIosModule):
self.execute_module(changed=True, commands=commands)
def test_ios_banner_nochange(self):
- banner_text = load_fixture('ios_banner_show_banner.txt').strip()
+ banner_text = load_fixture('ios_banner_show_banner.txt')
set_module_args(dict(banner='login', text=banner_text))
self.execute_module()
class TestIosBannerIos12Module(TestIosBannerModule):
- def load_fixtures(self, commands):
- show_banner_return_value = (1, '', None)
- show_running_config_return_value = \
- (0, load_fixture('ios_banner_show_running_config_ios12.txt').strip(), None)
- self.exec_command.side_effect = [show_banner_return_value,
- show_running_config_return_value]
+ def load_fixtures(self, commands=None):
+ def load_from_file(*args, **kwargs):
+ return load_fixture('ios_banner_show_running_config_ios12.txt')
+ self.get_config.side_effect = load_from_file
def test_ios_banner_nochange(self):
- banner_text = load_fixture('ios_banner_show_banner.txt').strip()
+ banner_text = load_fixture('ios_banner_show_banner.txt')
set_module_args(dict(banner='exec', text=banner_text))
self.execute_module()
| 0
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/modules/network/ios/test_ios_banner.py F [100%]
=================================== FAILURES ===================================
_________________ TestIosBannerModule.test_ios_banner_nochange _________________
self = <units.modules.network.ios.test_ios_banner.TestIosBannerModule testMethod=test_ios_banner_nochange>
def setUp(self):
super(TestIosBannerModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config')
> self.get_config = self.mock_get_config.start()
test/units/modules/network/ios/test_ios_banner.py:34:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1378: in start
result = self.__enter__()
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1247: in __enter__
original, local = self.get_original()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <unittest.mock._patch object at 0x7fa60c725320>
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
original = target.__dict__[name]
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if name in _builtins and isinstance(target, ModuleType):
self.create = True
if not self.create and original is DEFAULT:
raise AttributeError(
> "%s does not have the attribute %r" % (target, name)
)
E AttributeError: <module 'ansible.modules.network.ios.ios_banner' from '/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/modules/network/ios/ios_banner.py'> does not have the attribute 'get_config'
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1221: AttributeError
=========================== 1 failed in 0.13 seconds ===========================
RUN EVERY COMMAND
1
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerModule::test_ios_banner_nochange
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/modules/network/ios/test_ios_banner.py F [100%]
=================================== FAILURES ===================================
______________ TestIosBannerIos12Module.test_ios_banner_nochange _______________
self = <units.modules.network.ios.test_ios_banner.TestIosBannerIos12Module testMethod=test_ios_banner_nochange>
def setUp(self):
super(TestIosBannerModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config')
> self.get_config = self.mock_get_config.start()
test/units/modules/network/ios/test_ios_banner.py:34:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1378: in start
result = self.__enter__()
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1247: in __enter__
original, local = self.get_original()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <unittest.mock._patch object at 0x7f933e989240>
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
original = target.__dict__[name]
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if name in _builtins and isinstance(target, ModuleType):
self.create = True
if not self.create and original is DEFAULT:
raise AttributeError(
> "%s does not have the attribute %r" % (target, name)
)
E AttributeError: <module 'ansible.modules.network.ios.ios_banner' from '/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/site-packages/ansible-2.10.0.dev0-py3.6.egg/ansible/modules/network/ios/ios_banner.py'> does not have the attribute 'get_config'
/opt/conda/envs/bdadf60111059c1c5aebbf31698bc2b1/lib/python3.6/unittest/mock.py:1221: AttributeError
=========================== 1 failed in 0.12 seconds =========================== | pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerModule::test_ios_banner_nochange
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerIos12Module::test_ios_banner_nochange | da07b98b7a433493728ddb7ac7efbd20b8988776 | test/units/modules/network/ios/test_ios_banner.py |
ansible__ansible-18 | ansible/ansible | diff --git a/lib/ansible/cli/galaxy.py b/lib/ansible/cli/galaxy.py
index 4ff114ec70..66c45a723c 100644
--- a/lib/ansible/cli/galaxy.py
+++ b/lib/ansible/cli/galaxy.py
@@ -55,7 +55,7 @@ class GalaxyCLI(CLI):
''' create an options parser for bin/ansible '''
super(GalaxyCLI, self).init_parser(
- desc="Perform various Role related operations.",
+ desc="Perform various Role and Collection related operations.",
)
# common
@@ -413,7 +413,7 @@ class GalaxyCLI(CLI):
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)]
inject_data = dict(
- description='your description',
+ description='your {0} description'.format(galaxy_type),
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'),
)
if galaxy_type == 'role':
@@ -525,7 +525,7 @@ class GalaxyCLI(CLI):
if not os.path.exists(b_dir_path):
os.makedirs(b_dir_path)
- display.display("- %s was created successfully" % obj_name)
+ display.display("- %s %s was created successfully" % (galaxy_type.title(), obj_name))
def execute_info(self):
"""
| diff --git a/test/units/cli/test_galaxy.py b/test/units/cli/test_galaxy.py
index c63dc3e21f..e9ba9b8ee8 100644
--- a/test/units/cli/test_galaxy.py
+++ b/test/units/cli/test_galaxy.py
@@ -494,7 +494,7 @@ def test_collection_default(collection_skeleton):
assert metadata['authors'] == ['your name <example@domain.com>']
assert metadata['readme'] == 'README.md'
assert metadata['version'] == '1.0.0'
- assert metadata['description'] == 'your description'
+ assert metadata['description'] == 'your collection description'
assert metadata['license'] == ['GPL-2.0-or-later']
assert metadata['tags'] == []
assert metadata['dependencies'] == {}
@@ -637,7 +637,7 @@ def test_collection_build(collection_artifact):
assert coll_info['authors'] == ['your name <example@domain.com>']
assert coll_info['readme'] == 'README.md'
assert coll_info['tags'] == []
- assert coll_info['description'] == 'your description'
+ assert coll_info['description'] == 'your collection description'
assert coll_info['license'] == ['GPL-2.0-or-later']
assert coll_info['license_file'] is None
assert coll_info['dependencies'] == {}
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/cli/test_galaxy.py F [100%]
=================================== FAILURES ===================================
________________ test_collection_default[collection_skeleton0] _________________
collection_skeleton = '/tmp/pytest-of-root/pytest-6/test-ÅÑŚÌβŁÈ Collections0/ansible_test/my_collection'
@pytest.mark.parametrize('collection_skeleton', [
('ansible_test.my_collection', None),
], indirect=True)
def test_collection_default(collection_skeleton):
meta_path = os.path.join(collection_skeleton, 'galaxy.yml')
with open(meta_path, 'r') as galaxy_meta:
metadata = yaml.safe_load(galaxy_meta)
assert metadata['namespace'] == 'ansible_test'
assert metadata['name'] == 'my_collection'
assert metadata['authors'] == ['your name <example@domain.com>']
assert metadata['readme'] == 'README.md'
assert metadata['version'] == '1.0.0'
> assert metadata['description'] == 'your collection description'
E AssertionError: assert 'your description' == 'your collection description'
E - your description
E + your collection description
test/units/cli/test_galaxy.py:497: AssertionError
---------------------------- Captured stdout setup -----------------------------
- ansible_test.my_collection was created successfully
=========================== 1 failed in 2.16 seconds =========================== | pytest test/units/cli/test_galaxy.py::test_collection_default | bb1256ca9aa4c22225dbeef0ef23a20fa9388b2f | test/units/cli/test_galaxy.py |
ansible__ansible-14 | ansible/ansible | diff --git a/lib/ansible/galaxy/api.py b/lib/ansible/galaxy/api.py
index da53f2e70c..ed9be32af3 100644
--- a/lib/ansible/galaxy/api.py
+++ b/lib/ansible/galaxy/api.py
@@ -21,6 +21,12 @@ from ansible.module_utils.urls import open_url
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
+try:
+ from urllib.parse import urlparse
+except ImportError:
+ # Python 2
+ from urlparse import urlparse
+
display = Display()
@@ -289,14 +295,20 @@ class GalaxyAPI:
data = self._call_galaxy(url)
results = data['results']
done = (data.get('next_link', None) is None)
+
+ # https://github.com/ansible/ansible/issues/64355
+ # api_server contains part of the API path but next_link includes the the /api part so strip it out.
+ url_info = urlparse(self.api_server)
+ base_url = "%s://%s/" % (url_info.scheme, url_info.netloc)
+
while not done:
- url = _urljoin(self.api_server, data['next_link'])
+ url = _urljoin(base_url, data['next_link'])
data = self._call_galaxy(url)
results += data['results']
done = (data.get('next_link', None) is None)
except Exception as e:
- display.vvvv("Unable to retrive role (id=%s) data (%s), but this is not fatal so we continue: %s"
- % (role_id, related, to_text(e)))
+ display.warning("Unable to retrieve role (id=%s) data (%s), but this is not fatal so we continue: %s"
+ % (role_id, related, to_text(e)))
return results
@g_connect(['v1'])
| diff --git a/test/units/galaxy/test_api.py b/test/units/galaxy/test_api.py
index 11fd435f0e..7464a7d7f4 100644
--- a/test/units/galaxy/test_api.py
+++ b/test/units/galaxy/test_api.py
@@ -860,3 +860,50 @@ def test_get_collection_versions_pagination(api_version, token_type, token_ins,
assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[2][2]['headers']['Authorization'] == '%s my token' % token_type
+
+
+@pytest.mark.parametrize('responses', [
+ [
+ {
+ 'count': 2,
+ 'results': [{'name': '3.5.1', }, {'name': '3.5.2'}],
+ 'next_link': None,
+ 'next': None,
+ 'previous_link': None,
+ 'previous': None
+ },
+ ],
+ [
+ {
+ 'count': 2,
+ 'results': [{'name': '3.5.1'}],
+ 'next_link': '/api/v1/roles/432/versions/?page=2&page_size=50',
+ 'next': '/roles/432/versions/?page=2&page_size=50',
+ 'previous_link': None,
+ 'previous': None
+ },
+ {
+ 'count': 2,
+ 'results': [{'name': '3.5.2'}],
+ 'next_link': None,
+ 'next': None,
+ 'previous_link': '/api/v1/roles/432/versions/?&page_size=50',
+ 'previous': '/roles/432/versions/?page_size=50',
+ },
+ ]
+])
+def test_get_role_versions_pagination(monkeypatch, responses):
+ api = get_test_galaxy_api('https://galaxy.com/api/', 'v1')
+
+ mock_open = MagicMock()
+ mock_open.side_effect = [StringIO(to_text(json.dumps(r))) for r in responses]
+ monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
+
+ actual = api.fetch_role_related('versions', 432)
+ assert actual == [{'name': '3.5.1'}, {'name': '3.5.2'}]
+
+ assert mock_open.call_count == len(responses)
+
+ assert mock_open.mock_calls[0][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page_size=50'
+ if len(responses) == 2:
+ assert mock_open.mock_calls[1][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page=2&page_size=50'
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 2 items
test/units/galaxy/test_api.py .F [100%]
=================================== FAILURES ===================================
________________ test_get_role_versions_pagination[responses1] _________________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7fc933a42400>
responses = [{'count': 2, 'next': '/roles/432/versions/?page=2&page_size=50', 'next_link': '/api/v1/roles/432/versions/?page=2&pag...ious': None, ...}, {'count': 2, 'next': None, 'next_link': None, 'previous': '/roles/432/versions/?page_size=50', ...}]
@pytest.mark.parametrize('responses', [
[
{
'count': 2,
'results': [{'name': '3.5.1', }, {'name': '3.5.2'}],
'next_link': None,
'next': None,
'previous_link': None,
'previous': None
},
],
[
{
'count': 2,
'results': [{'name': '3.5.1'}],
'next_link': '/api/v1/roles/432/versions/?page=2&page_size=50',
'next': '/roles/432/versions/?page=2&page_size=50',
'previous_link': None,
'previous': None
},
{
'count': 2,
'results': [{'name': '3.5.2'}],
'next_link': None,
'next': None,
'previous_link': '/api/v1/roles/432/versions/?&page_size=50',
'previous': '/roles/432/versions/?page_size=50',
},
]
])
def test_get_role_versions_pagination(monkeypatch, responses):
api = get_test_galaxy_api('https://galaxy.com/api/', 'v1')
mock_open = MagicMock()
mock_open.side_effect = [StringIO(to_text(json.dumps(r))) for r in responses]
monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
actual = api.fetch_role_related('versions', 432)
assert actual == [{'name': '3.5.1'}, {'name': '3.5.2'}]
assert mock_open.call_count == len(responses)
assert mock_open.mock_calls[0][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page_size=50'
if len(responses) == 2:
> assert mock_open.mock_calls[1][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page=2&page_size=50'
E AssertionError: assert 'https://gala...&page_size=50' == 'https://galax...&page_size=50'
E - https://galaxy.com/api/api/v1/roles/432/versions/?page=2&page_size=50
E ? ----
E + https://galaxy.com/api/v1/roles/432/versions/?page=2&page_size=50
test/units/galaxy/test_api.py:909: AssertionError
====================== 1 failed, 1 passed in 1.75 seconds ====================== | pytest test/units/galaxy/test_api.py::test_get_role_versions_pagination | a1ab093ddbd32f1002cbf6d6f184c7d0041d890d | test/units/galaxy/test_api.py |
ansible__ansible-5 | ansible/ansible | diff --git a/lib/ansible/module_utils/common/validation.py b/lib/ansible/module_utils/common/validation.py
index 4c29c8b234..fc13f4d0aa 100644
--- a/lib/ansible/module_utils/common/validation.py
+++ b/lib/ansible/module_utils/common/validation.py
@@ -189,7 +189,7 @@ def check_required_arguments(argument_spec, module_parameters):
missing.append(k)
if missing:
- msg = "missing required arguments: %s" % ", ".join(missing)
+ msg = "missing required arguments: %s" % ", ".join(sorted(missing))
raise TypeError(to_native(msg))
return missing
diff --git a/test/units/module_utils/common/validation/test_check_mutually_exclusive.py b/test/units/module_utils/common/validation/test_check_mutually_exclusive.py
index 5d44f85151..7bf90760b1 100644
--- a/test/units/module_utils/common/validation/test_check_mutually_exclusive.py
+++ b/test/units/module_utils/common/validation/test_check_mutually_exclusive.py
@@ -34,11 +34,12 @@ def test_check_mutually_exclusive_found(mutually_exclusive_terms):
'fox': 'red',
'socks': 'blue',
}
- expected = "TypeError('parameters are mutually exclusive: string1|string2, box|fox|socks',)"
+ expected = "parameters are mutually exclusive: string1|string2, box|fox|socks"
with pytest.raises(TypeError) as e:
check_mutually_exclusive(mutually_exclusive_terms, params)
- assert e.value == expected
+
+ assert to_native(e.value) == expected
def test_check_mutually_exclusive_none():
@@ -53,4 +54,4 @@ def test_check_mutually_exclusive_none():
def test_check_mutually_exclusive_no_params(mutually_exclusive_terms):
with pytest.raises(TypeError) as te:
check_mutually_exclusive(mutually_exclusive_terms, None)
- assert "TypeError: 'NoneType' object is not iterable" in to_native(te.error)
+ assert "'NoneType' object is not iterable" in to_native(te.value)
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/module_utils/common/validation/test_check_required_arguments.py F [100%]
=================================== FAILURES ===================================
________________ test_check_required_arguments_missing_multiple ________________
arguments_terms_multiple = {'bar': {'required': True}, 'foo': {'required': True}, 'tomato': {'irrelevant': 72}}
def test_check_required_arguments_missing_multiple(arguments_terms_multiple):
params = {
'apples': 'woohoo',
}
expected = "missing required arguments: bar, foo"
with pytest.raises(TypeError) as e:
check_required_arguments(arguments_terms_multiple, params)
> assert to_native(e.value) == expected
E AssertionError: assert 'missing requ...nts: foo, bar' == 'missing requi...nts: bar, foo'
E - missing required arguments: foo, bar
E ? -----
E + missing required arguments: bar, foo
E ? +++++
test/units/module_utils/common/validation/test_check_required_arguments.py:73: AssertionError
=========================== 1 failed in 0.14 seconds =========================== | pytest test/units/module_utils/common/validation/test_check_required_arguments.py::test_check_required_arguments_missing_multiple | 2af76f16be8cf2239daaec4c2f31c3dcb4e3469e | test/units/module_utils/common/validation/test_check_required_arguments.py |
|
ansible__ansible-16 | ansible/ansible | diff --git a/lib/ansible/module_utils/facts/hardware/linux.py b/lib/ansible/module_utils/facts/hardware/linux.py
index befc2fb5e7..503a6e3b73 100644
--- a/lib/ansible/module_utils/facts/hardware/linux.py
+++ b/lib/ansible/module_utils/facts/hardware/linux.py
@@ -242,8 +242,9 @@ class LinuxHardware(Hardware):
# The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
# and sometimes includes both 'processor' and 'Processor'.
- # Always use 'processor' count for ARM systems
- if collected_facts.get('ansible_architecture', '').startswith(('armv', 'aarch')):
+ # The fields for Power CPUs include 'processor' and 'cpu'.
+ # Always use 'processor' count for ARM and Power systems
+ if collected_facts.get('ansible_architecture', '').startswith(('armv', 'aarch', 'ppc')):
i = processor_occurence
# FIXME
diff --git a/test/units/module_utils/facts/hardware/linux_data.py b/test/units/module_utils/facts/hardware/linux_data.py
index ba2e528d7a..05dc0e6513 100644
--- a/test/units/module_utils/facts/hardware/linux_data.py
+++ b/test/units/module_utils/facts/hardware/linux_data.py
@@ -495,9 +495,9 @@ CPU_INFO_TEST_SCENARIOS = [
'7', 'POWER7 (architected), altivec supported'
],
'processor_cores': 1,
- 'processor_count': 16,
+ 'processor_count': 8,
'processor_threads_per_core': 1,
- 'processor_vcpus': 16
+ 'processor_vcpus': 8
},
},
{
@@ -531,9 +531,9 @@ CPU_INFO_TEST_SCENARIOS = [
'23', 'POWER8 (architected), altivec supported',
],
'processor_cores': 1,
- 'processor_count': 48,
+ 'processor_count': 24,
'processor_threads_per_core': 1,
- 'processor_vcpus': 48
+ 'processor_vcpus': 24
},
},
{
| diff --git a/test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py b/test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py
index 542ed4bce2..cda251e4ea 100644
--- a/test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py
+++ b/test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py
@@ -26,13 +26,13 @@ def test_get_cpu_info_missing_arch(mocker):
module = mocker.Mock()
inst = linux.LinuxHardware(module)
- # ARM will report incorrect processor count if architecture is not available
+ # ARM and Power will report incorrect processor count if architecture is not available
mocker.patch('os.path.exists', return_value=False)
mocker.patch('os.access', return_value=True)
for test in CPU_INFO_TEST_SCENARIOS:
mocker.patch('ansible.module_utils.facts.hardware.linux.get_file_lines', side_effect=[[], test['cpuinfo']])
test_result = inst.get_cpu_facts()
- if test['architecture'].startswith(('armv', 'aarch')):
+ if test['architecture'].startswith(('armv', 'aarch', 'ppc')):
assert test['expected_result'] != test_result
else:
assert test['expected_result'] == test_result
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
plugins: mock-1.2
collected 1 item
test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py F [100%]
=================================== FAILURES ===================================
________________________ test_get_cpu_info_missing_arch ________________________
mocker = <pytest_mock.MockFixture object at 0x7f6572412978>
def test_get_cpu_info_missing_arch(mocker):
module = mocker.Mock()
inst = linux.LinuxHardware(module)
# ARM and Power will report incorrect processor count if architecture is not available
mocker.patch('os.path.exists', return_value=False)
mocker.patch('os.access', return_value=True)
for test in CPU_INFO_TEST_SCENARIOS:
mocker.patch('ansible.module_utils.facts.hardware.linux.get_file_lines', side_effect=[[], test['cpuinfo']])
test_result = inst.get_cpu_facts()
if test['architecture'].startswith(('armv', 'aarch', 'ppc')):
> assert test['expected_result'] != test_result
E AssertionError: assert {'processor': ['0', 'POWER7 (architected), altivec supported', '1', 'POWER7 (architected), altivec supported', '2', 'P...hitected), altivec supported', ...], 'processor_cores': 1, 'processor_count': 16, 'processor_threads_per_core': 1, ...} != {'processor': ['0', 'POWER7 (architected), altivec supported', '1', 'POWER7 (architected), altivec supported', '2', 'P...hitected), altivec supported', ...], 'processor_cores': 1, 'processor_count': 16, 'processor_threads_per_core': 1, ...}
test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py:36: AssertionError
=========================== 1 failed in 0.25 seconds =========================== | pytest test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py::test_get_cpu_info_missing_arch | 2a9964ede8b2b77a62a005f6f5abc964b2819b0e | test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py |
ansible__ansible-1 | ansible/ansible | diff --git a/lib/ansible/galaxy/collection.py b/lib/ansible/galaxy/collection.py
index a055b08e71..856e54666f 100644
--- a/lib/ansible/galaxy/collection.py
+++ b/lib/ansible/galaxy/collection.py
@@ -668,6 +668,11 @@ def verify_collections(collections, search_paths, apis, validate_certs, ignore_e
for search_path in search_paths:
b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict')
if os.path.isdir(b_search_path):
+ if not os.path.isfile(os.path.join(to_text(b_search_path, errors='surrogate_or_strict'), 'MANIFEST.json')):
+ raise AnsibleError(
+ message="Collection %s does not appear to have a MANIFEST.json. " % collection_name +
+ "A MANIFEST.json is expected if the collection has been built and installed via ansible-galaxy."
+ )
local_collection = CollectionRequirement.from_path(b_search_path, False)
break
if local_collection is None:
| diff --git a/test/units/galaxy/test_collection.py b/test/units/galaxy/test_collection.py
index f6b285cca0..1fced76933 100644
--- a/test/units/galaxy/test_collection.py
+++ b/test/units/galaxy/test_collection.py
@@ -1154,6 +1154,25 @@ def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man
assert mock_debug.call_args_list[-1][0][0] == success_msg
+@patch.object(os.path, 'isdir', return_value=True)
+def test_verify_collections_no_version(mock_isdir, mock_collection, monkeypatch):
+ namespace = 'ansible_namespace'
+ name = 'collection'
+ version = '*' # Occurs if MANIFEST.json does not exist
+
+ local_collection = mock_collection(namespace=namespace, name=name, version=version)
+ monkeypatch.setattr(collection.CollectionRequirement, 'from_path', MagicMock(return_value=local_collection))
+
+ collections = [('%s.%s' % (namespace, name), version, None)]
+
+ with pytest.raises(AnsibleError) as err:
+ collection.verify_collections(collections, './', local_collection.api, False, False)
+
+ err_msg = 'Collection %s.%s does not appear to have a MANIFEST.json. ' % (namespace, name)
+ err_msg += 'A MANIFEST.json is expected if the collection has been built and installed via ansible-galaxy.'
+ assert err.value.message == err_msg
+
+
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_not_installed(mock_verify, mock_collection, monkeypatch):
namespace = 'ansible_namespace'
@@ -1208,11 +1227,14 @@ def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
-def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection):
+def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection, monkeypatch):
namespace = 'ansible_namespace'
name = 'collection'
version = '1.0.0'
+ monkeypatch.setattr(os.path, 'isfile', MagicMock(side_effect=[False, True]))
+ monkeypatch.setattr(collection.CollectionRequirement, 'from_path', MagicMock(return_value=mock_collection()))
+
collections = [('%s.%s' % (namespace, name), version, None)]
search_path = './'
validate_certs = False
@@ -1227,12 +1249,13 @@ def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection):
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
-def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection):
+def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection, monkeypatch):
namespace = 'ansible_namespace'
name = 'collection'
version = '1.0.0'
- local_collection = mock_collection(local_installed=False)
+ monkeypatch.setattr(os.path, 'isfile', MagicMock(side_effect=[False, True]))
+ monkeypatch.setattr(collection.CollectionRequirement, 'from_path', MagicMock(return_value=mock_collection()))
collections = [('%s.%s' % (namespace, name), version, None)]
search_path = './'
@@ -1292,13 +1315,14 @@ def test_verify_collections_url(monkeypatch):
assert err.value.message == msg
-@patch.object(os.path, 'isfile', return_value=False)
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
-def test_verify_collections_name(mock_verify, mock_isdir, mock_isfile, mock_collection, monkeypatch):
+def test_verify_collections_name(mock_verify, mock_isdir, mock_collection, monkeypatch):
local_collection = mock_collection()
monkeypatch.setattr(collection.CollectionRequirement, 'from_path', MagicMock(return_value=local_collection))
+ monkeypatch.setattr(os.path, 'isfile', MagicMock(side_effect=[False, True, False]))
+
located_remote_from_name = MagicMock(return_value=mock_collection(local=False))
monkeypatch.setattr(collection.CollectionRequirement, 'from_name', located_remote_from_name)
| ============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.10.1, py-1.11.0, pluggy-0.13.1
rootdir: /home/user/BugsInPy/temp/projects/ansible, inifile:
collected 1 item
test/units/galaxy/test_collection.py F [100%]
=================================== FAILURES ===================================
______________________ test_verify_collections_no_version ______________________
mock_isdir = <MagicMock name='isdir' id='140281683441872'>
mock_collection = <function mock_collection.<locals>.create_mock_collection at 0x7f95de240d08>
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f95dfe8f438>
@patch.object(os.path, 'isdir', return_value=True)
def test_verify_collections_no_version(mock_isdir, mock_collection, monkeypatch):
namespace = 'ansible_namespace'
name = 'collection'
version = '*' # Occurs if MANIFEST.json does not exist
local_collection = mock_collection(namespace=namespace, name=name, version=version)
monkeypatch.setattr(collection.CollectionRequirement, 'from_path', MagicMock(return_value=local_collection))
collections = [('%s.%s' % (namespace, name), version, None)]
with pytest.raises(AnsibleError) as err:
> collection.verify_collections(collections, './', local_collection.api, False, False)
test/units/galaxy/test_collection.py:1169:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/conda/envs/e91cde33ffcafb3e40ee0f44cab38afc/lib/python3.6/site-packages/ansible_base-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:679: in verify_collections
allow_pre_release=allow_pre_release)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
collection = 'ansible_namespace.collection'
apis = <ansible.galaxy.api.GalaxyAPI object at 0x7f95dfe85c88>
requirement = '*', force = False, parent = None, allow_pre_release = False
@staticmethod
def from_name(collection, apis, requirement, force, parent=None, allow_pre_release=False):
namespace, name = collection.split('.', 1)
galaxy_meta = None
> for api in apis:
E TypeError: 'GalaxyAPI' object is not iterable
/opt/conda/envs/e91cde33ffcafb3e40ee0f44cab38afc/lib/python3.6/site-packages/ansible_base-2.10.0.dev0-py3.6.egg/ansible/galaxy/collection.py:442: TypeError
=========================== 1 failed in 7.92 seconds =========================== | pytest test/units/galaxy/test_collection.py::test_verify_collections_no_version | 25c5388fdec9e56517a93feb5e8d485680946c25 | test/units/galaxy/test_collection.py |
psf__black-19 | psf/black | diff --git a/black.py b/black.py
index 15a7547..a03b9aa 100644
--- a/black.py
+++ b/black.py
@@ -1044,6 +1044,10 @@ class EmptyLineTracker:
# Don't insert empty lines between decorators.
return 0, 0
+ if is_decorator and self.previous_line and self.previous_line.is_comment:
+ # Don't insert empty lines between decorator comments.
+ return 0, 0
+
newlines = 2
if current_line.depth:
newlines -= 1
| diff --git a/tests/test_black.py b/tests/test_black.py
index dd3beed..9c029df 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -626,6 +626,14 @@ class BlackTestCase(unittest.TestCase):
)
self.assertEqual(result.exit_code, 1)
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_comment_in_decorator(self) -> None:
+ source, expected = read_data("comments6")
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, line_length=ll)
+
if __name__ == "__main__":
unittest.main()
| Expected tree:
file_input
decorated
decorators
decorator
AT '@'
NAME 'property'
NEWLINE '\n'
/decorator
decorator
AT '# TODO: X\n' '@'
NAME 'property'
NEWLINE '\n'
/decorator
decorator
AT '# TODO: Y\n# TODO: Z\n' '@'
NAME 'property'
NEWLINE '\n'
/decorator
/decorators
funcdef
NAME 'def'
NAME ' ' 'foo'
parameters
LPAR '('
RPAR ')'
/parameters
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
NAME 'pass'
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/funcdef
/decorated
ENDMARKER ''
/file_input
Actual tree:
file_input
decorated
decorators
decorator
AT '@'
NAME 'property'
NEWLINE '\n'
/decorator
decorator
AT '# TODO: X\n\n\n' '@'
NAME 'property'
NEWLINE '\n'
/decorator
decorator
AT '# TODO: Y\n# TODO: Z\n\n\n' '@'
NAME 'property'
NEWLINE '\n'
/decorator
/decorators
funcdef
NAME 'def'
NAME ' ' 'foo'
parameters
LPAR '('
RPAR ')'
/parameters
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
NAME 'pass'
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/funcdef
/decorated
ENDMARKER ''
/file_input
======================================================================
FAIL: test_comment_in_decorator (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/9eb237635523606f4da80fce5b96935a/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 633, in test_comment_in_decorator
self.assertFormatEqual(expected, actual)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 100, in assertFormatEqual
self.assertEqual(expected, actual)
AssertionError: '@pro[13 chars]: X\n@property\n# TODO: Y\n# TODO: Z\n@propert[21 chars]ss\n' != '@pro[13 chars]: X\n\n\n@property\n# TODO: Y\n# TODO: Z\n\n\n[29 chars]ss\n'
@property
# TODO: X
+
+
@property
# TODO: Y
# TODO: Z
+
+
@property
def foo():
pass
----------------------------------------------------------------------
Ran 1 test in 0.019s
FAILED (failures=1) | python -m unittest -q tests.test_black.BlackTestCase.test_comment_in_decorator | 337a4199f90ca48a19cf26511e0cec330b13bd4e | tests/comments6.py;tests/test_black.py |
psf__black-4 | psf/black | diff --git a/black.py b/black.py
index f7022d8..05edf1a 100644
--- a/black.py
+++ b/black.py
@@ -1480,7 +1480,13 @@ class EmptyLineTracker:
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
- before -= self.previous_after
+ before = (
+ # Black should not insert empty lines at the beginning
+ # of the file
+ 0
+ if self.previous_line is None
+ else before - self.previous_after
+ )
self.previous_after = after
self.previous_line = current_line
return before, after
| diff --git a/tests/test_black.py b/tests/test_black.py
index 7b3a8b6..015243f 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -639,6 +639,14 @@ class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_beginning_backslash(self) -> None:
+ source, expected = read_data("beginning_backslash")
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, black.FileMode())
+
def test_tab_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n"
| Expected tree:
file_input
simple_stmt
power
NAME 'print'
trailer
LPAR '('
STRING '"hello, world"'
RPAR ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
ENDMARKER ''
/file_input
Actual tree:
file_input
simple_stmt
power
NAME '\n\n' 'print'
trailer
LPAR '('
STRING '"hello, world"'
RPAR ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
ENDMARKER ''
/file_input
======================================================================
FAIL: test_beginning_backslash (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/6720714fabfb1cf1ab2248b54d458923/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 646, in test_beginning_backslash
self.assertFormatEqual(expected, actual)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 168, in assertFormatEqual
self.assertEqual(expected, actual)
AssertionError: 'print("hello, world")\n' != '\n\nprint("hello, world")\n'
+
+
print("hello, world")
----------------------------------------------------------------------
Ran 1 test in 0.051s
FAILED (failures=1) | python -m unittest -q tests.test_black.BlackTestCase.test_beginning_backslash | 65ea568e3301951f26e0e3b98f6d5dc80132e917 | tests/test_black.py;tests/data/beginning_backslash.py |
psf__black-13 | psf/black | diff --git a/blib2to3/pgen2/tokenize.py b/blib2to3/pgen2/tokenize.py
index 9a7664b..1f51ff0 100644
--- a/blib2to3/pgen2/tokenize.py
+++ b/blib2to3/pgen2/tokenize.py
@@ -516,13 +516,14 @@ def generate_tokens(readline):
stashed = tok
continue
- if token == 'def':
+ if token in ('def', 'for'):
if (stashed
and stashed[0] == NAME
and stashed[1] == 'async'):
- async_def = True
- async_def_indent = indents[-1]
+ if token == 'def':
+ async_def = True
+ async_def_indent = indents[-1]
yield (ASYNC, stashed[1],
stashed[2], stashed[3],
| diff --git a/tests/test_black.py b/tests/test_black.py
index 10d7f28..9c798ca 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -411,6 +411,16 @@ class BlackTestCase(unittest.TestCase):
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, line_length=ll, mode=mode)
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_python37(self) -> None:
+ source, expected = read_data("python37")
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ major, minor = sys.version_info[:2]
+ if major > 3 or (major == 3 and minor >= 7):
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, line_length=ll)
+
@patch("black.dump_to_file", dump_to_stderr)
def test_fmtonoff(self) -> None:
source, expected = read_data("fmtonoff")
| ======================================================================
ERROR: test_python37 (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/f55af976068fc1252014f3b7e1dbdb4f/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 417, in test_python37
actual = fs(source)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 610, in format_str
src_node = lib2to3_parse(src_contents)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 681, in lib2to3_parse
raise exc from None
ValueError: Cannot parse: 4:16: return (i*2 async for i in arange(42))
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1) | python -m unittest -q tests.test_black.BlackTestCase.test_python37 | b719d85ccc330170e40b2617307a7e3b2a0bab14 | tests/data/python37.py;tests/test_black.py |
psf__black-22 | psf/black | diff --git a/black.py b/black.py
index dab3f00..6499b22 100644
--- a/black.py
+++ b/black.py
@@ -3,14 +3,25 @@
import asyncio
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
-from functools import partial
+from functools import partial, wraps
import keyword
import os
from pathlib import Path
import tokenize
import sys
from typing import (
- Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, Type, TypeVar, Union
+ Callable,
+ Dict,
+ Generic,
+ Iterable,
+ Iterator,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
)
from attr import dataclass, Factory
@@ -32,7 +43,9 @@ Depth = int
NodeType = int
LeafID = int
Priority = int
+Index = int
LN = Union[Leaf, Node]
+SplitFunc = Callable[['Line', bool], Iterator['Line']]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg='red', err=True)
@@ -520,7 +533,7 @@ class Line:
depth: int = 0
leaves: List[Leaf] = Factory(list)
- comments: Dict[LeafID, Leaf] = Factory(dict)
+ comments: List[Tuple[Index, Leaf]] = Factory(list)
bracket_tracker: BracketTracker = Factory(BracketTracker)
inside_brackets: bool = False
has_for: bool = False
@@ -549,16 +562,31 @@ class Line:
self.bracket_tracker.mark(leaf)
self.maybe_remove_trailing_comma(leaf)
self.maybe_increment_for_loop_variable(leaf)
- if self.maybe_adapt_standalone_comment(leaf):
- return
if not self.append_comment(leaf):
self.leaves.append(leaf)
+ def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
+ """Like :func:`append()` but disallow invalid standalone comment structure.
+
+ Raises ValueError when any `leaf` is appended after a standalone comment
+ or when a standalone comment is not the first leaf on the line.
+ """
+ if self.bracket_tracker.depth == 0:
+ if self.is_comment:
+ raise ValueError("cannot append to standalone comments")
+
+ if self.leaves and leaf.type == STANDALONE_COMMENT:
+ raise ValueError(
+ "cannot append standalone comments to a populated line"
+ )
+
+ self.append(leaf, preformatted=preformatted)
+
@property
def is_comment(self) -> bool:
"""Is this line a standalone comment?"""
- return bool(self) and self.leaves[0].type == STANDALONE_COMMENT
+ return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
@property
def is_decorator(self) -> bool:
@@ -622,6 +650,15 @@ class Line:
and self.leaves[0].value == 'yield'
)
+ @property
+ def contains_standalone_comments(self) -> bool:
+ """If so, needs to be split before emitting."""
+ for leaf in self.leaves:
+ if leaf.type == STANDALONE_COMMENT:
+ return True
+
+ return False
+
def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
"""Remove trailing comma if there is one and it's safe."""
if not (
@@ -632,13 +669,13 @@ class Line:
return False
if closing.type == token.RBRACE:
- self.leaves.pop()
+ self.remove_trailing_comma()
return True
if closing.type == token.RSQB:
comma = self.leaves[-1]
if comma.parent and comma.parent.type == syms.listmaker:
- self.leaves.pop()
+ self.remove_trailing_comma()
return True
# For parens let's check if it's safe to remove the comma. If the
@@ -666,7 +703,7 @@ class Line:
break
if commas > 1:
- self.leaves.pop()
+ self.remove_trailing_comma()
return True
return False
@@ -694,52 +731,49 @@ class Line:
return False
- def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool:
- """Hack a standalone comment to act as a trailing comment for line splitting.
-
- If this line has brackets and a standalone `comment`, we need to adapt
- it to be able to still reformat the line.
-
- This is not perfect, the line to which the standalone comment gets
- appended will appear "too long" when splitting.
- """
- if not (
+ def append_comment(self, comment: Leaf) -> bool:
+ """Add an inline or standalone comment to the line."""
+ if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
+ comment.prefix = ''
return False
- comment.type = token.COMMENT
- comment.prefix = '\n' + ' ' * (self.depth + 1)
- return self.append_comment(comment)
-
- def append_comment(self, comment: Leaf) -> bool:
- """Add an inline comment to the line."""
if comment.type != token.COMMENT:
return False
- try:
- after = id(self.last_non_delimiter())
- except LookupError:
+ after = len(self.leaves) - 1
+ if after == -1:
comment.type = STANDALONE_COMMENT
comment.prefix = ''
return False
else:
- if after in self.comments:
- self.comments[after].value += str(comment)
- else:
- self.comments[after] = comment
+ self.comments.append((after, comment))
return True
- def last_non_delimiter(self) -> Leaf:
- """Return the last non-delimiter on the line. Raise LookupError otherwise."""
- for i in range(len(self.leaves)):
- last = self.leaves[-i - 1]
- if not is_delimiter(last):
- return last
+ def comments_after(self, leaf: Leaf) -> Iterator[Leaf]:
+ """Generate comments that should appear directly after `leaf`."""
+ for _leaf_index, _leaf in enumerate(self.leaves):
+ if leaf is _leaf:
+ break
+
+ else:
+ return
- raise LookupError("No non-delimiters found")
+ for index, comment_after in self.comments:
+ if _leaf_index == index:
+ yield comment_after
+
+ def remove_trailing_comma(self) -> None:
+ """Remove the trailing comma and moves the comments attached to it."""
+ comma_index = len(self.leaves) - 1
+ for i in range(len(self.comments)):
+ comment_index, comment = self.comments[i]
+ if comment_index == comma_index:
+ self.comments[i] = (comma_index - 1, comment)
+ self.leaves.pop()
def __str__(self) -> str:
"""Render the line."""
@@ -752,7 +786,7 @@ class Line:
res = f'{first.prefix}{indent}{first.value}'
for leaf in leaves:
res += str(leaf)
- for comment in self.comments.values():
+ for _, comment in self.comments:
res += str(comment)
return res + '\n'
@@ -809,10 +843,6 @@ class UnformattedLines(Line):
"""Does nothing and returns False."""
return False
- def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool:
- """Does nothing and returns False."""
- return False
-
@dataclass
class EmptyLineTracker:
@@ -1439,23 +1469,24 @@ def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
- if isinstance(line, UnformattedLines):
+ if isinstance(line, UnformattedLines) or line.is_comment:
yield line
return
line_str = str(line).strip('\n')
- if len(line_str) <= line_length and '\n' not in line_str:
+ if (
+ len(line_str) <= line_length
+ and '\n' not in line_str # multiline strings
+ and not line.contains_standalone_comments
+ ):
yield line
return
+ split_funcs: List[SplitFunc]
if line.is_def:
split_funcs = [left_hand_split]
elif line.inside_brackets:
- split_funcs = [delimiter_split]
- if '\n' not in line_str:
- # Only attempt RHS if we don't have multiline strings or comments
- # on this line.
- split_funcs.append(right_hand_split)
+ split_funcs = [delimiter_split, standalone_comment_split, right_hand_split]
else:
split_funcs = [right_hand_split]
for split_func in split_funcs:
@@ -1464,7 +1495,7 @@ def split_line(
# split altogether.
result: List[Line] = []
try:
- for l in split_func(line, py36=py36):
+ for l in split_func(line, py36):
if str(l).strip('\n') == line_str:
raise CannotSplit("Split function returned an unchanged result")
@@ -1517,8 +1548,7 @@ def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
- comment_after = line.comments.get(id(leaf))
- if comment_after:
+ for comment_after in line.comments_after(leaf):
result.append(comment_after, preformatted=True)
bracket_split_succeeded_or_raise(head, body, tail)
for result in (head, body, tail):
@@ -1557,8 +1587,7 @@ def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
- comment_after = line.comments.get(id(leaf))
- if comment_after:
+ for comment_after in line.comments_after(leaf):
result.append(comment_after, preformatted=True)
bracket_split_succeeded_or_raise(head, body, tail)
for result in (head, body, tail):
@@ -1592,10 +1621,25 @@ def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None
)
+def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
+ """Normalize prefix of the first leaf in every line returned by `split_func`.
+
+ This is a decorator over relevant split functions.
+ """
+
+ @wraps(split_func)
+ def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
+ for l in split_func(line, py36):
+ normalize_prefix(l.leaves[0], inside_brackets=True)
+ yield l
+
+ return split_wrapper
+
+
+@dont_increase_indentation
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
"""Split according to delimiters of the highest priority.
- This kind of split doesn't increase indentation.
If `py36` is True, the split will add trailing commas also in function
signatures that contain `*` and `**`.
"""
@@ -1615,11 +1659,24 @@ def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
lowest_depth = sys.maxsize
trailing_comma_safe = True
+
+ def append_to_line(leaf: Leaf) -> Iterator[Line]:
+ """Append `leaf` to current line or to new line if appending impossible."""
+ nonlocal current_line
+ try:
+ current_line.append_safe(leaf, preformatted=True)
+ except ValueError as ve:
+ yield current_line
+
+ current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
+ current_line.append(leaf)
+
for leaf in line.leaves:
- current_line.append(leaf, preformatted=True)
- comment_after = line.comments.get(id(leaf))
- if comment_after:
- current_line.append(comment_after, preformatted=True)
+ yield from append_to_line(leaf)
+
+ for comment_after in line.comments_after(leaf):
+ yield from append_to_line(comment_after)
+
lowest_depth = min(lowest_depth, leaf.bracket_depth)
if (
leaf.bracket_depth == lowest_depth
@@ -1629,7 +1686,6 @@ def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
trailing_comma_safe = trailing_comma_safe and py36
leaf_priority = delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
- normalize_prefix(current_line.leaves[0], inside_brackets=True)
yield current_line
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
@@ -1640,7 +1696,40 @@ def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
and trailing_comma_safe
):
current_line.append(Leaf(token.COMMA, ','))
- normalize_prefix(current_line.leaves[0], inside_brackets=True)
+ yield current_line
+
+
+@dont_increase_indentation
+def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
+ """Split standalone comments from the rest of the line."""
+ for leaf in line.leaves:
+ if leaf.type == STANDALONE_COMMENT:
+ if leaf.bracket_depth == 0:
+ break
+
+ else:
+ raise CannotSplit("Line does not have any standalone comments")
+
+ current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
+
+ def append_to_line(leaf: Leaf) -> Iterator[Line]:
+ """Append `leaf` to current line or to new line if appending impossible."""
+ nonlocal current_line
+ try:
+ current_line.append_safe(leaf, preformatted=True)
+ except ValueError as ve:
+ yield current_line
+
+ current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
+ current_line.append(leaf)
+
+ for leaf in line.leaves:
+ yield from append_to_line(leaf)
+
+ for comment_after in line.comments_after(leaf):
+ yield from append_to_line(comment_after)
+
+ if current_line:
yield current_line
| diff --git a/tests/test_black.py b/tests/test_black.py
index 759bda5..9d7f579 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -150,6 +150,14 @@ class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_comments3(self) -> None:
+ source, expected = read_data('comments3')
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, line_length=ll)
+
@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data('cantfit')
| Expected tree:
file_input
funcdef
NAME 'def'
NAME ' ' 'func'
parameters
LPAR '('
RPAR ')'
/parameters
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
expr_stmt
NAME 'lcomp3'
EQUAL ' ' '='
atom
LSQB ' ' '['
listmaker
power
NAME '\n # This one is actually too long to fit in a single line.\n ' 'element'
trailer
DOT '.'
NAME 'split'
/trailer
trailer
LPAR '('
arglist
STRING "'\\n'"
COMMA ','
NUMBER ' ' '1'
/arglist
RPAR ')'
/trailer
trailer
LSQB '['
NUMBER '0'
RSQB ']'
/trailer
/power
old_comp_for
NAME '\n # yup\n ' 'for'
NAME ' ' 'element'
NAME ' ' 'in'
power
NAME ' ' 'collection'
trailer
DOT '.'
NAME 'select_elements'
/trailer
trailer
LPAR '('
RPAR ')'
/trailer
/power
old_comp_if
NAME '\n # right\n ' 'if'
comparison
NAME ' ' 'element'
comp_op
NAME ' ' 'is'
NAME ' ' 'not'
/comp_op
NAME ' ' 'None'
/comparison
/old_comp_if
/old_comp_for
/listmaker
RSQB '\n ' ']'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
if_stmt
NAME ' # Capture each of the exceptions in the MultiError along with each of their causes and contexts\n ' 'if'
power
NAME ' ' 'isinstance'
trailer
LPAR '('
arglist
NAME 'exc_value'
COMMA ','
NAME ' ' 'MultiError'
/arglist
RPAR ')'
/trailer
/power
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
expr_stmt
NAME 'embedded'
EQUAL ' ' '='
atom
LSQB ' ' '['
RSQB ']'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
for_stmt
NAME ' ' 'for'
NAME ' ' 'exc'
NAME ' ' 'in'
power
NAME ' ' 'exc_value'
trailer
DOT '.'
NAME 'exceptions'
/trailer
/power
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
if_stmt
NAME 'if'
comparison
NAME ' ' 'exc'
comp_op
NAME ' ' 'not'
NAME ' ' 'in'
/comp_op
NAME ' ' '_seen'
/comparison
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
power
NAME 'embedded'
trailer
DOT '.'
NAME 'append'
/trailer
trailer
LPAR '('
power
NAME '\n # This should be left alone (before)\n ' 'traceback'
trailer
DOT '.'
NAME 'TracebackException'
/trailer
trailer
DOT '.'
NAME 'from_exception'
/trailer
trailer
LPAR '('
arglist
NAME '\n ' 'exc'
COMMA ','
argument
NAME '\n ' 'limit'
EQUAL '='
NAME 'limit'
/argument
COMMA ','
argument
NAME '\n ' 'lookup_lines'
EQUAL '='
NAME 'lookup_lines'
/argument
COMMA ','
argument
NAME '\n ' 'capture_locals'
EQUAL '='
NAME 'capture_locals'
/argument
COMMA ','
argument
NAME '\n # copy the set of _seen exceptions so that duplicates\n # shared between sub-exceptions are not omitted\n ' '_seen'
EQUAL '='
power
NAME 'set'
trailer
LPAR '('
NAME '_seen'
RPAR ')'
/trailer
/power
/argument
COMMA ','
/arglist
RPAR '\n ' ')'
/trailer
/power
RPAR '\n # This should be left alone (after)\n ' ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/if_stmt
DEDENT ''
/suite
/for_stmt
DEDENT ''
/suite
/if_stmt
simple_stmt
power
NAME "\n # everything is fine if the expression isn't nested\n " 'traceback'
trailer
DOT '.'
NAME 'TracebackException'
/trailer
trailer
DOT '.'
NAME 'from_exception'
/trailer
trailer
LPAR '('
arglist
NAME '\n ' 'exc'
COMMA ','
argument
NAME '\n ' 'limit'
EQUAL '='
NAME 'limit'
/argument
COMMA ','
argument
NAME '\n ' 'lookup_lines'
EQUAL '='
NAME 'lookup_lines'
/argument
COMMA ','
argument
NAME '\n ' 'capture_locals'
EQUAL '='
NAME 'capture_locals'
/argument
COMMA ','
argument
NAME '\n # copy the set of _seen exceptions so that duplicates\n # shared between sub-exceptions are not omitted\n ' '_seen'
EQUAL '='
power
NAME 'set'
trailer
LPAR '('
NAME '_seen'
RPAR ')'
/trailer
/power
/argument
COMMA ','
/arglist
RPAR '\n ' ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/funcdef
ENDMARKER ''
/file_input
Actual tree:
file_input
funcdef
NAME 'def'
NAME ' ' 'func'
parameters
LPAR '('
RPAR ')'
/parameters
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
expr_stmt
NAME 'lcomp3'
EQUAL ' ' '='
atom
LSQB ' ' '['
listmaker
power
NAME '\n # This one is actually too long to fit in a single line.\n ' 'element'
trailer
DOT '.'
NAME 'split'
/trailer
trailer
LPAR '('
arglist
STRING "'\\n'"
COMMA ','
NUMBER ' ' '1'
/arglist
RPAR ')'
/trailer
trailer
LSQB '['
NUMBER '0'
RSQB ']'
/trailer
/power
old_comp_for
NAME '\n # yup\n ' 'for'
NAME ' ' 'element'
NAME ' ' 'in'
power
NAME ' ' 'collection'
trailer
DOT '.'
NAME 'select_elements'
/trailer
trailer
LPAR '('
RPAR ')'
/trailer
/power
old_comp_if
NAME '\n # right\n ' 'if'
comparison
NAME ' ' 'element'
comp_op
NAME ' ' 'is'
NAME ' ' 'not'
/comp_op
NAME ' ' 'None'
/comparison
/old_comp_if
/old_comp_for
/listmaker
RSQB '\n ' ']'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
if_stmt
NAME ' # Capture each of the exceptions in the MultiError along with each of their causes and contexts\n ' 'if'
power
NAME ' ' 'isinstance'
trailer
LPAR '('
arglist
NAME 'exc_value'
COMMA ','
NAME ' ' 'MultiError'
/arglist
RPAR ')'
/trailer
/power
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
expr_stmt
NAME 'embedded'
EQUAL ' ' '='
atom
LSQB ' ' '['
RSQB ']'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
for_stmt
NAME ' ' 'for'
NAME ' ' 'exc'
NAME ' ' 'in'
power
NAME ' ' 'exc_value'
trailer
DOT '.'
NAME 'exceptions'
/trailer
/power
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
if_stmt
NAME 'if'
comparison
NAME ' ' 'exc'
comp_op
NAME ' ' 'not'
NAME ' ' 'in'
/comp_op
NAME ' ' '_seen'
/comparison
COLON ':'
suite
NEWLINE '\n'
INDENT ' '
simple_stmt
power
NAME 'embedded'
trailer
DOT '.'
NAME 'append'
/trailer
trailer
LPAR '('
power
NAME '\n # This should be left alone (before)\n ' 'traceback'
trailer
DOT '.'
NAME 'TracebackException'
/trailer
trailer
DOT '.'
NAME 'from_exception'
/trailer
trailer
LPAR '('
arglist
NAME 'exc'
COMMA ','
argument
NAME ' ' 'limit'
EQUAL '='
NAME 'limit'
/argument
COMMA ','
argument
NAME ' ' 'lookup_lines'
EQUAL '='
NAME 'lookup_lines'
/argument
COMMA ','
argument
NAME ' ' 'capture_locals'
EQUAL '='
NAME 'capture_locals'
/argument
COMMA ','
argument
NAME ' ' '_seen'
EQUAL '='
power
NAME 'set'
trailer
LPAR '('
NAME '_seen'
RPAR ')'
/trailer
/power
/argument
/arglist
RPAR ')'
/trailer
/power
RPAR '\n # copy the set of _seen exceptions so that duplicates\n # shared between sub-exceptions are not omitted\n # This should be left alone (after)\n ' ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/if_stmt
DEDENT ''
/suite
/for_stmt
DEDENT ''
/suite
/if_stmt
simple_stmt
power
NAME "\n # everything is fine if the expression isn't nested\n " 'traceback'
trailer
DOT '.'
NAME 'TracebackException'
/trailer
trailer
DOT '.'
NAME 'from_exception'
/trailer
trailer
LPAR '('
arglist
NAME '\n ' 'exc'
COMMA ','
argument
NAME '\n ' 'limit'
EQUAL '='
NAME 'limit'
/argument
COMMA ','
argument
NAME '\n ' 'lookup_lines'
EQUAL '='
NAME 'lookup_lines'
/argument
COMMA ','
argument
NAME '\n ' 'capture_locals'
EQUAL '='
NAME 'capture_locals'
/argument
COMMA ','
argument
NAME '\n # copy the set of _seen exceptions so that duplicates\n # shared between sub-exceptions are not omitted\n ' '_seen'
EQUAL '='
power
NAME 'set'
trailer
LPAR '('
NAME '_seen'
RPAR ')'
/trailer
/power
/argument
COMMA ','
/arglist
RPAR '\n ' ')'
/trailer
/power
NEWLINE '\n'
/simple_stmt
DEDENT ''
/suite
/funcdef
ENDMARKER ''
/file_input
======================================================================
FAIL: test_comments3 (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/5d5ee738c2357f585e30916fc41aee1f/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 157, in test_comments3
self.assertFormatEqual(expected, actual)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 69, in assertFormatEqual
self.assertEqual(expected, actual)
AssertionError: "def [645 chars]tion(\n exc,\n [802 chars] )\n" != "def [645 chars]tion(exc, limit=limit, lookup_lines=lookup_lin[645 chars] )\n"
def func():
lcomp3 = [
# This one is actually too long to fit in a single line.
element.split('\n', 1)[0]
# yup
for element in collection.select_elements()
# right
if element is not None
]
# Capture each of the exceptions in the MultiError along with each of their causes and contexts
if isinstance(exc_value, MultiError):
embedded = []
for exc in exc_value.exceptions:
if exc not in _seen:
embedded.append(
# This should be left alone (before)
+ traceback.TracebackException.from_exception(exc, limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals, _seen=set(_seen))
- traceback.TracebackException.from_exception(
- exc,
- limit=limit,
- lookup_lines=lookup_lines,
- capture_locals=capture_locals,
- # copy the set of _seen exceptions so that duplicates
? ----
+ # copy the set of _seen exceptions so that duplicates
- # shared between sub-exceptions are not omitted
? ----
+ # shared between sub-exceptions are not omitted
- _seen=set(_seen),
- )
# This should be left alone (after)
)
# everything is fine if the expression isn't nested
traceback.TracebackException.from_exception(
exc,
limit=limit,
lookup_lines=lookup_lines,
capture_locals=capture_locals,
# copy the set of _seen exceptions so that duplicates
# shared between sub-exceptions are not omitted
_seen=set(_seen),
)
----------------------------------------------------------------------
Ran 1 test in 0.049s
FAILED (failures=1) | python -m unittest -q tests.test_black.BlackTestCase.test_comments3 | 728c56c986bc5aea4d9897d3fce3159f89991b8e | tests/comments3.py;tests/test_black.py |
psf__black-9 | psf/black | diff --git a/black.py b/black.py
index b727666..c44bc9b 100644
--- a/black.py
+++ b/black.py
@@ -726,13 +726,13 @@ def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
return GRAMMARS
elif all(not version.is_python2() for version in target_versions):
- # Python 2-compatible code, so don't try Python 3 grammar.
+ # Python 3-compatible code, so don't try Python 2 grammar
return [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
]
else:
- return [pygram.python_grammar]
+ return [pygram.python_grammar_no_print_statement, pygram.python_grammar]
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
| diff --git a/tests/test_black.py b/tests/test_black.py
index 7c99f00..645eec7 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -461,6 +461,14 @@ class BlackTestCase(unittest.TestCase):
# black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_python2_print_function(self) -> None:
+ source, expected = read_data("python2_print_function")
+ mode = black.FileMode(target_versions={black.TargetVersion.PY27})
+ actual = fs(source, mode=mode)
+ self.assertFormatEqual(expected, actual)
+ black.assert_stable(source, actual, mode)
+
@patch("black.dump_to_file", dump_to_stderr)
def test_python2_unicode_literals(self) -> None:
source, expected = read_data("python2_unicode_literals")
| ======================================================================
ERROR: test_python2_print_function (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/aec4dc0199f1038f500bf70b52d8047b/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 468, in test_python2_print_function
actual = fs(source, mode=mode)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 669, in format_str
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 758, in lib2to3_parse
raise exc from None
black.InvalidInput: Cannot parse: 6:13: print(a, file=sys.stderr)
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1) | python -m unittest -q tests.test_black.BlackTestCase.test_python2_print_function | 026c81b83454f176a9f9253cbfb70be2c159d822 | tests/data/python2_print_function.py;tests/test_black.py |
psf__black-7 | psf/black | diff --git a/black.py b/black.py
index cada4d0..7bfcfca 100644
--- a/black.py
+++ b/black.py
@@ -2726,6 +2726,14 @@ def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
+ # Add parentheses around long tuple unpacking in assignments.
+ if (
+ index == 0
+ and isinstance(child, Node)
+ and child.type == syms.testlist_star_expr
+ ):
+ check_lpar = True
+
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child, parent=node):
@@ -2757,7 +2765,11 @@ def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
- node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
+ prefix = child.prefix
+ child.prefix = ""
+ new_child = Node(syms.atom, [lpar, child, rpar])
+ new_child.prefix = prefix
+ node.insert_child(index, new_child)
check_lpar = isinstance(child, Leaf) and child.value in parens_after
| diff --git a/tests/test_black.py b/tests/test_black.py
index 86175aa..896ad0c 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -542,6 +542,14 @@ class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_tuple_assign(self) -> None:
+ source, expected = read_data("tupleassign")
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, black.FileMode())
+
def test_tab_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n"
| Expected tree:
file_input
simple_stmt
expr_stmt
atom
LPAR '('
testlist_gexp
NAME '\n ' 'sdfjklsdfsjldkflkjsf'
COMMA ','
NAME '\n ' 'sdfjsdfjlksdljkfsdlkf'
COMMA ','
NAME '\n ' 'sdfsdjfklsdfjlksdljkf'
COMMA ','
NAME '\n ' 'sdsfsdfjskdflsfsdf'
COMMA ','
/testlist_gexp
RPAR '\n' ')'
/atom
EQUAL ' ' '='
atom
LPAR ' ' '('
testlist_gexp
NUMBER '1'
COMMA ','
NUMBER ' ' '2'
COMMA ','
NUMBER ' ' '3'
/testlist_gexp
RPAR ')'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
ENDMARKER ''
/file_input
Actual tree:
file_input
simple_stmt
expr_stmt
testlist_star_expr
NAME 'sdfjklsdfsjldkflkjsf'
COMMA ','
NAME ' ' 'sdfjsdfjlksdljkfsdlkf'
COMMA ','
NAME ' ' 'sdfsdjfklsdfjlksdljkf'
COMMA ','
NAME ' ' 'sdsfsdfjskdflsfsdf'
/testlist_star_expr
EQUAL ' ' '='
atom
LPAR ' ' '('
testlist_gexp
NUMBER '\n ' '1'
COMMA ','
NUMBER '\n ' '2'
COMMA ','
NUMBER '\n ' '3'
COMMA ','
/testlist_gexp
RPAR '\n' ')'
/atom
/expr_stmt
NEWLINE '\n'
/simple_stmt
ENDMARKER ''
/file_input
======================================================================
FAIL: test_tuple_assign (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/b657706be35f360ba710368e4ce42a52/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 549, in test_tuple_assign
self.assertFormatEqual(expected, actual)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 159, in assertFormatEqual
self.assertEqual(expected, actual)
AssertionError: '(\n sdfjklsdfsjldkflkjsf,\n sdfjsdf[81 chars]3)\n' != 'sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdl[74 chars]n)\n'
+ sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = (
+ 1,
+ 2,
+ 3,
+ )
- (
- sdfjklsdfsjldkflkjsf,
- sdfjsdfjlksdljkfsdlkf,
- sdfsdjfklsdfjlksdljkf,
- sdsfsdfjskdflsfsdf,
- ) = (1, 2, 3)
----------------------------------------------------------------------
Ran 1 test in 0.008s
FAILED (failures=1) | python -m unittest -q tests.test_black.BlackTestCase.test_tuple_assign | 18119d38466652ae818436cb497f601294ed4558 | tests/data/tupleassign.py;tests/test_black.py |
psf__black-12 | psf/black | diff --git a/black.py b/black.py
index 85cb45b..0f166c6 100644
--- a/black.py
+++ b/black.py
@@ -877,8 +877,8 @@ class BracketTracker:
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
- _for_loop_variable: int = 0
- _lambda_arguments: int = 0
+ _for_loop_depths: List[int] = Factory(list)
+ _lambda_argument_depths: List[int] = Factory(list)
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with bracket-related metadata. Keep track of delimiters.
@@ -951,16 +951,21 @@ class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
- self._for_loop_variable += 1
+ self._for_loop_depths.append(self.depth)
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for_loop_variable` above for explanation."""
- if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
+ if (
+ self._for_loop_depths
+ and self._for_loop_depths[-1] == self.depth
+ and leaf.type == token.NAME
+ and leaf.value == "in"
+ ):
self.depth -= 1
- self._for_loop_variable -= 1
+ self._for_loop_depths.pop()
return True
return False
@@ -973,16 +978,20 @@ class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
- self._lambda_arguments += 1
+ self._lambda_argument_depths.append(self.depth)
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_lambda_arguments` above for explanation."""
- if self._lambda_arguments and leaf.type == token.COLON:
+ if (
+ self._lambda_argument_depths
+ and self._lambda_argument_depths[-1] == self.depth
+ and leaf.type == token.COLON
+ ):
self.depth -= 1
- self._lambda_arguments -= 1
+ self._lambda_argument_depths.pop()
return True
return False
| diff --git a/tests/test_black.py b/tests/test_black.py
index 9c798ca..311f635 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -453,6 +453,14 @@ class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
+ @patch("black.dump_to_file", dump_to_stderr)
+ def test_bracket_match(self) -> None:
+ source, expected = read_data("bracketmatch")
+ actual = fs(source)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(source, actual)
+ black.assert_stable(source, actual, line_length=ll)
+
def test_report_verbose(self) -> None:
report = black.Report(verbose=True)
out_lines = []
| ======================================================================
ERROR: test_bracket_match (tests.test_black.BlackTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/conda/envs/5cb45a3af35d91ebe6796d6535bfc272/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 459, in test_bracket_match
actual = fs(source)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 626, in format_str
for current_line in lines.visit(src_node):
File "/home/user/BugsInPy/temp/projects/black/black.py", line 714, in visit
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 1454, in visit_default
yield from super().visit_default(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 720, in visit_default
yield from self.visit(child)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 714, in visit
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 1495, in visit_stmt
yield from self.visit(child)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 714, in visit
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 1454, in visit_default
yield from super().visit_default(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 720, in visit_default
yield from self.visit(child)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 714, in visit
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 1453, in visit_default
self.current_line.append(node)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 1029, in append
self.bracket_tracker.mark(leaf)
File "/home/user/BugsInPy/temp/projects/black/black.py", line 905, in mark
opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
KeyError: (0, 8)
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1) | python -m unittest -q tests.test_black.BlackTestCase.test_bracket_match | 8b340e210271a8108995fd479c55dbc0a34466bd | tests/data/bracketmatch.py;tests/test_black.py |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 47