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): [email protected]('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 <[email protected]>'] 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 <[email protected]>'] 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 <[email protected]>'] 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 + + [email protected]('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 [email protected](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 [email protected](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
psf__black-6
psf/black
diff --git a/black.py b/black.py index c96d205..c8aa30b 100644 --- a/black.py +++ b/black.py @@ -48,6 +48,7 @@ from blib2to3 import pygram, pytree from blib2to3.pgen2 import driver, token from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError +from blib2to3.pgen2.tokenize import TokenizerConfig __version__ = "19.3b0" @@ -136,19 +137,28 @@ class Feature(Enum): NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 + # The following two feature-flags are mutually exclusive, and exactly one should be + # set for every version of python. + ASYNC_IS_VALID_IDENTIFIER = 6 + ASYNC_IS_RESERVED_KEYWORD = 7 VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { - TargetVersion.PY27: set(), - TargetVersion.PY33: {Feature.UNICODE_LITERALS}, - TargetVersion.PY34: {Feature.UNICODE_LITERALS}, - TargetVersion.PY35: {Feature.UNICODE_LITERALS, Feature.TRAILING_COMMA_IN_CALL}, + TargetVersion.PY27: {Feature.ASYNC_IS_VALID_IDENTIFIER}, + TargetVersion.PY33: {Feature.UNICODE_LITERALS, Feature.ASYNC_IS_VALID_IDENTIFIER}, + TargetVersion.PY34: {Feature.UNICODE_LITERALS, Feature.ASYNC_IS_VALID_IDENTIFIER}, + TargetVersion.PY35: { + Feature.UNICODE_LITERALS, + Feature.TRAILING_COMMA_IN_CALL, + Feature.ASYNC_IS_VALID_IDENTIFIER, + }, TargetVersion.PY36: { Feature.UNICODE_LITERALS, Feature.F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, + Feature.ASYNC_IS_VALID_IDENTIFIER, }, TargetVersion.PY37: { Feature.UNICODE_LITERALS, @@ -156,6 +166,7 @@ VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, + Feature.ASYNC_IS_RESERVED_KEYWORD, }, TargetVersion.PY38: { Feature.UNICODE_LITERALS, @@ -163,6 +174,7 @@ VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, + Feature.ASYNC_IS_RESERVED_KEYWORD, }, } @@ -748,20 +760,62 @@ def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: return tiow.read(), encoding, newline -def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: +@dataclass(frozen=True) +class ParserConfig: + grammar: Grammar + tokenizer_config: TokenizerConfig = TokenizerConfig() + + +def get_parser_configs(target_versions: Set[TargetVersion]) -> List[ParserConfig]: if not target_versions: # No target_version specified, so try all grammars. return [ - pygram.python_grammar_no_print_statement_no_exec_statement, - pygram.python_grammar_no_print_statement, - pygram.python_grammar, + # Python 3.7+ + ParserConfig( + pygram.python_grammar_no_print_statement_no_exec_statement, + TokenizerConfig(async_is_reserved_keyword=True), + ), + # Python 3.0-3.6 + ParserConfig( + pygram.python_grammar_no_print_statement_no_exec_statement, + TokenizerConfig(async_is_reserved_keyword=False), + ), + # Python 2.7 with future print_function import + ParserConfig(pygram.python_grammar_no_print_statement), + # Python 2.7 + ParserConfig(pygram.python_grammar), ] elif all(version.is_python2() for version in target_versions): # Python 2-only code, so try Python 2 grammars. - return [pygram.python_grammar_no_print_statement, pygram.python_grammar] + return [ + # Python 2.7 with future print_function import + ParserConfig(pygram.python_grammar_no_print_statement), + # Python 2.7 + ParserConfig(pygram.python_grammar), + ] else: # Python 3-compatible code, so only try Python 3 grammar. - return [pygram.python_grammar_no_print_statement_no_exec_statement] + configs = [] + # If we have to parse both, try to parse async as a keyword first + if not supports_feature(target_versions, Feature.ASYNC_IS_VALID_IDENTIFIER): + # Python 3.7+ + configs.append( + ParserConfig( + pygram.python_grammar_no_print_statement_no_exec_statement, + TokenizerConfig(async_is_reserved_keyword=True), + ) + ) + if not supports_feature(target_versions, Feature.ASYNC_IS_RESERVED_KEYWORD): + # Python 3.0-3.6 + configs.append( + ParserConfig( + pygram.python_grammar_no_print_statement_no_exec_statement, + TokenizerConfig(async_is_reserved_keyword=False), + ) + ) + # At least one of the above branches must have been taken, because every Python + # version has exactly one of the two 'ASYNC_IS_*' flags + return configs def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node: @@ -769,8 +823,12 @@ def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) - if src_txt[-1:] != "\n": src_txt += "\n" - for grammar in get_grammars(set(target_versions)): - drv = driver.Driver(grammar, pytree.convert) + for parser_config in get_parser_configs(set(target_versions)): + drv = driver.Driver( + parser_config.grammar, + pytree.convert, + tokenizer_config=parser_config.tokenizer_config, + ) try: result = drv.parse_string(src_txt, True) break diff --git a/blib2to3/pgen2/driver.py b/blib2to3/pgen2/driver.py index 63b60bb..e681b52 100644 --- a/blib2to3/pgen2/driver.py +++ b/blib2to3/pgen2/driver.py @@ -29,12 +29,19 @@ from . import grammar, parse, token, tokenize, pgen class Driver(object): - def __init__(self, grammar, convert=None, logger=None): + def __init__( + self, + grammar, + convert=None, + logger=None, + tokenizer_config=tokenize.TokenizerConfig(), + ): self.grammar = grammar if logger is None: logger = logging.getLogger(__name__) self.logger = logger self.convert = convert + self.tokenizer_config = tokenizer_config def parse_tokens(self, tokens, debug=False): """Parse a series of tokens and return the syntax tree.""" @@ -97,7 +104,7 @@ class Driver(object): def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" - tokens = tokenize.generate_tokens(stream.readline) + tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config) return self.parse_tokens(tokens, debug) def parse_stream(self, stream, debug=False): @@ -111,7 +118,10 @@ class Driver(object): def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" - tokens = tokenize.generate_tokens(io.StringIO(text).readline) + tokens = tokenize.generate_tokens( + io.StringIO(text).readline, + config=self.tokenizer_config, + ) return self.parse_tokens(tokens, debug) def _partially_consume_prefix(self, prefix, column): diff --git a/blib2to3/pgen2/tokenize.py b/blib2to3/pgen2/tokenize.py index 1f51ff0..43e1d59 100644 --- a/blib2to3/pgen2/tokenize.py +++ b/blib2to3/pgen2/tokenize.py @@ -31,6 +31,7 @@ __credits__ = \ import re from codecs import BOM_UTF8, lookup +from attr import dataclass from blib2to3.pgen2.token import * from . import token @@ -137,6 +138,10 @@ single_quoted = ( tabsize = 8 +@dataclass(frozen=True) +class TokenizerConfig: + async_is_reserved_keyword: bool = False + class TokenError(Exception): pass class StopTokenizing(Exception): pass @@ -334,7 +339,7 @@ def untokenize(iterable): ut = Untokenizer() return ut.untokenize(iterable) -def generate_tokens(readline): +def generate_tokens(readline, config: TokenizerConfig = TokenizerConfig()): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the @@ -356,6 +361,9 @@ def generate_tokens(readline): contline = None indents = [0] + # If we know we're parsing 3.7+, we can unconditionally parse `async` and + # `await` as keywords. + async_is_reserved_keyword = config.async_is_reserved_keyword # 'stashed' and 'async_*' are used for async/await parsing stashed = None async_def = False @@ -506,7 +514,7 @@ def generate_tokens(readline): yield (STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): - if async_def: + if async_is_reserved_keyword or async_def: yield (ASYNC if token == 'async' else AWAIT, token, spos, epos, line) continue diff --git a/tests/data/python37.py b/tests/data/python37.py index 9781ff6..4401b7b 100644 --- a/tests/data/python37.py +++ b/tests/data/python37.py @@ -14,6 +14,14 @@ async def func(): self.async_inc, arange(8), batch_size=3 ) ] + +def awaited_generator_value(n): + return (await awaitable for awaitable in awaitable_list) + +def make_arange(n): + return (i * 2 for i in range(n) if await wrap(i)) + + # output @@ -39,3 +47,11 @@ async def func(): self.async_inc, arange(8), batch_size=3 ) ] + + +def awaited_generator_value(n): + return (await awaitable for awaitable in awaitable_list) + + +def make_arange(n): + return (i * 2 for i in range(n) if await wrap(i))
diff --git a/tests/test_black.py b/tests/test_black.py index 59343ef..0ea4ac5 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -502,8 +502,24 @@ class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, mode) + @patch("black.dump_to_file", dump_to_stderr) + def test_async_as_identifier(self) -> None: + source_path = (THIS_DIR / "data" / "async_as_identifier.py").resolve() + source, expected = read_data("async_as_identifier") + 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, black.FileMode()) + # ensure black can parse this when the target is 3.6 + self.invokeBlack([str(source_path), "--target-version", "py36"]) + # but not on 3.7, because async/await is no longer an identifier + self.invokeBlack([str(source_path), "--target-version", "py37"], exit_code=123) + @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: + source_path = (THIS_DIR / "data" / "python37.py").resolve() source, expected = read_data("python37") actual = fs(source) self.assertFormatEqual(expected, actual) @@ -511,6 +527,10 @@ class BlackTestCase(unittest.TestCase): if major > 3 or (major == 3 and minor >= 7): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) + # ensure black can parse this when the target is 3.7 + self.invokeBlack([str(source_path), "--target-version", "py37"]) + # but not on 3.6, because we use async as a reserved keyword + self.invokeBlack([str(source_path), "--target-version", "py36"], exit_code=123) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff(self) -> None:
0 ====================================================================== ERROR: test_async_as_identifier (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/9a5e1cb72f6ccedabd1a075e4161dd27/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 508, in test_async_as_identifier source, expected = read_data("async_as_identifier") File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 64, in read_data with open(base_dir / name, "r", encoding="utf8") as test: FileNotFoundError: [Errno 2] No such file or directory: '/home/user/BugsInPy/temp/projects/black/tests/data/async_as_identifier.py' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) RUN EVERY COMMAND 1 python -m unittest -q tests.test_black.BlackTestCase.test_async_as_identifier ====================================================================== FAIL: test_python37 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/9a5e1cb72f6ccedabd1a075e4161dd27/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 533, in test_python37 self.invokeBlack([str(source_path), "--target-version", "py36"], exit_code=123) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 168, in invokeBlack self.assertEqual(result.exit_code, exit_code, msg=runner.stderr_bytes.decode()) AssertionError: 0 != 123 : All done! ✨ 🍰 ✨ 1 file left unchanged. ---------------------------------------------------------------------- Ran 1 test in 0.131s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_async_as_identifier python -m unittest -q tests.test_black.BlackTestCase.test_python37
8c8adedc2a74a494c24f93e405b6418ac32f54cd
tests/test_black.py;tests/data/comment_after_escaped_newline.py
psf__black-2
psf/black
diff --git a/black.py b/black.py index 2df03f7..e55e4fe 100644 --- a/black.py +++ b/black.py @@ -3116,18 +3116,49 @@ def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: - is_fmt_on = False - for comment in list_comments(container.prefix, is_endmarker=False): - if comment.value in FMT_ON: - is_fmt_on = True - elif comment.value in FMT_OFF: - is_fmt_on = False - if is_fmt_on: + if fmt_on(container): return - yield container + # fix for fmt: on in children + if contains_fmt_on_at_column(container, leaf.column): + for child in container.children: + if contains_fmt_on_at_column(child, leaf.column): + return + yield child + else: + yield container + container = container.next_sibling + - container = container.next_sibling +def fmt_on(container: LN) -> bool: + is_fmt_on = False + for comment in list_comments(container.prefix, is_endmarker=False): + if comment.value in FMT_ON: + is_fmt_on = True + elif comment.value in FMT_OFF: + is_fmt_on = False + return is_fmt_on + + +def contains_fmt_on_at_column(container: LN, column: int) -> bool: + for child in container.children: + if ( + isinstance(child, Node) + and first_leaf_column(child) == column + or isinstance(child, Leaf) + and child.column == column + ): + if fmt_on(child): + return True + + return False + + +def first_leaf_column(node: Node) -> Optional[int]: + for child in node.children: + if isinstance(child, Leaf): + return child.column + return None def maybe_make_parens_invisible_in_atom(node: LN, parent: LN) -> bool:
diff --git a/tests/test_black.py b/tests/test_black.py index 7a4a3bb..15b6341 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -632,6 +632,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_fmtonoff4(self) -> None: + source, expected = read_data("fmtonoff4") + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) def test_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_parentheses")
====================================================================== ERROR: test_fmtonoff4 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/9975e41e088302bd9e3d9af7a8db556f/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 637, in test_fmtonoff4 source, expected = read_data("fmtonoff4") File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 58, in read_data with open(base_dir / name, "r", encoding="utf8") as test: FileNotFoundError: [Errno 2] No such file or directory: '/home/user/BugsInPy/temp/projects/black/tests/data/fmtonoff4.py' ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (errors=1)
python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff4
c8ca6b2b9ff3510bee12129824cebfc2fc51e5b2
tests/test_black.py
psf__black-21
psf/black
diff --git a/black.py b/black.py index 537ba59..587d9b3 100644 --- a/black.py +++ b/black.py @@ -2325,7 +2325,7 @@ def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( - mode="w", prefix="blk_", suffix=".log", delete=False + mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8" ) as f: for lines in output: f.write(lines)
diff --git a/tests/test_black.py b/tests/test_black.py index f71f9b3..6e6aad8 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -150,7 +150,7 @@ class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) - with open(tmp_file) as f: + with open(tmp_file, encoding="utf8") as f: actual = f.read() finally: os.unlink(tmp_file)
---------------------------------------------------------------------- Ran 1 test in 0.162s OK
python -m unittest -q tests.test_black.BlackTestCase.test_expression_ff
c071af761e1550c6e4ebab8e5af747d2d8fdd48e
tests/test_black.py
psf__black-3
psf/black
diff --git a/black.py b/black.py index d9348a3..26a2915 100644 --- a/black.py +++ b/black.py @@ -394,7 +394,7 @@ def target_version_option_callback( @click.option( "--config", type=click.Path( - exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False + exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
diff --git a/tests/test_black.py b/tests/test_black.py index acbaade..7a4a3bb 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -1645,6 +1645,16 @@ class BlackTestCase(unittest.TestCase): raise result.exception self.assertEqual(result.exit_code, 0) + def test_invalid_config_return_code(self) -> None: + tmp_file = Path(black.dump_to_file()) + try: + tmp_config = Path(black.dump_to_file()) + tmp_config.unlink() + args = ["--config", str(tmp_config), str(tmp_file)] + self.invokeBlack(args, exit_code=2, ignore_config=False) + finally: + tmp_file.unlink() + class BlackDTestCase(AioHTTPTestCase): async def get_application(self) -> web.Application:
====================================================================== FAIL: test_invalid_config_return_code (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 1654, in test_invalid_config_return_code self.invokeBlack(args, exit_code=2, ignore_config=False) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 162, in invokeBlack self.assertEqual(result.exit_code, exit_code, msg=runner.stderr_bytes.decode()) AssertionError: 1 != 2 : Error: Could not open file /tmp/blk_ujgrsiio.log: Error reading configuration file: [Errno 2] No such file or directory: '/tmp/blk_ujgrsiio.log' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_invalid_config_return_code
8126b4f6a9342290de4655e6a8a78cd288ce7daa
tests/test_black.py
psf__black-10
psf/black
diff --git a/blib2to3/pgen2/driver.py b/blib2to3/pgen2/driver.py index 72d9f47..6626c05 100644 --- a/blib2to3/pgen2/driver.py +++ b/blib2to3/pgen2/driver.py @@ -131,10 +131,8 @@ class Driver(object): current_line = "" current_column = 0 wait_for_nl = False - elif char == ' ': + elif char in ' \t': current_column += 1 - elif char == '\t': - current_column += 4 elif char == '\n': # unexpected empty line current_column = 0
diff --git a/tests/test_black.py b/tests/test_black.py index b3f1f82..92031ca 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -509,6 +509,19 @@ class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) + def test_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" + + self.assertFormatEqual(fs(contents_spc), contents_spc) + self.assertFormatEqual(fs(contents_tab), contents_spc) + + contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t\t# comment\n\tpass\n" + contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n" + + self.assertFormatEqual(fs(contents_tab), contents_spc) + self.assertFormatEqual(fs(contents_spc), contents_spc) + def test_report_verbose(self) -> None: report = black.Report(verbose=True) out_lines = []
Expected tree: file_input if_stmt NAME 'if' NUMBER ' ' '1' COLON ':' suite NEWLINE '\n' INDENT '' if_stmt NAME ' ' 'if' NUMBER ' ' '2' COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' ' 'pass' NEWLINE '\n' /simple_stmt DEDENT ' # comment\n' '' /suite /if_stmt simple_stmt NAME ' ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /if_stmt ENDMARKER '' /file_input Actual tree: file_input if_stmt NAME 'if' NUMBER ' ' '1' COLON ':' suite NEWLINE '\n' INDENT '' if_stmt NAME ' ' 'if' NUMBER ' ' '2' COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /if_stmt simple_stmt NAME ' # comment\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /if_stmt ENDMARKER '' /file_input ====================================================================== FAIL: test_comment_indentation (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 517, in test_comment_indentation self.assertFormatEqual(fs(contents_tab), contents_spc) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 156, in assertFormatEqual self.assertEqual(expected, actual) AssertionError: 'if 1:\n if 2:\n pass\n # comment\n pass\n' != 'if 1:\n if 2:\n pass\n # comment\n pass\n' if 1: if 2: pass - # comment ? ---- + # comment pass ---------------------------------------------------------------------- Ran 1 test in 0.034s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_comment_indentation
f6643c4f0cfbae1f2493fdfce46cfbae3d26f46b
tests/test_black.py
psf__black-23
psf/black
diff --git a/black.py b/black.py index bb8ec2e..7935cdc 100644 --- a/black.py +++ b/black.py @@ -235,23 +235,36 @@ def format_str(src_contents: str, line_length: int) -> FileContent: return dst_contents +GRAMMARS = [ + pygram.python_grammar_no_print_statement_no_exec_statement, + pygram.python_grammar_no_print_statement, + pygram.python_grammar_no_exec_statement, + pygram.python_grammar, +] + + def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement - drv = driver.Driver(grammar, pytree.convert) if src_txt[-1] != '\n': nl = '\r\n' if '\r\n' in src_txt[:1024] else '\n' src_txt += nl - try: - result = drv.parse_string(src_txt, True) - except ParseError as pe: - lineno, column = pe.context[1] - lines = src_txt.splitlines() + for grammar in GRAMMARS: + drv = driver.Driver(grammar, pytree.convert) try: - faulty_line = lines[lineno - 1] - except IndexError: - faulty_line = "<line number missing in source>" - raise ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}") from None + result = drv.parse_string(src_txt, True) + break + + except ParseError as pe: + lineno, column = pe.context[1] + lines = src_txt.splitlines() + try: + faulty_line = lines[lineno - 1] + except IndexError: + faulty_line = "<line number missing in source>" + exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}") + else: + raise exc from None if isinstance(result, Leaf): result = Node(syms.file_input, [result]) @@ -903,6 +916,17 @@ def whitespace(leaf: Leaf) -> str: # noqa C901 ): return NO + elif ( + prevp.type == token.RIGHTSHIFT + and prevp.parent + and prevp.parent.type == syms.shift_expr + and prevp.prev_sibling + and prevp.prev_sibling.type == token.NAME + and prevp.prev_sibling.value == 'print' + ): + # Python 2 print chevron + return NO + elif prev.type in OPENING_BRACKETS: return NO @@ -1538,7 +1562,12 @@ def assert_equivalent(src: str, dst: str) -> None: try: src_ast = ast.parse(src) except Exception as exc: - raise AssertionError(f"cannot parse source: {exc}") from None + major, minor = sys.version_info[:2] + raise AssertionError( + f"cannot use --safe with this file; failed to parse source file " + f"with Python {major}.{minor}'s builtin AST. Re-run with --fast " + f"or stop using deprecated Python 2 syntax. AST error message: {exc}" + ) try: dst_ast = ast.parse(dst) diff --git a/blib2to3/pygram.py b/blib2to3/pygram.py index c4ff9d1..bf55ab4 100644 --- a/blib2to3/pygram.py +++ b/blib2to3/pygram.py @@ -36,5 +36,12 @@ python_symbols = Symbols(python_grammar) python_grammar_no_print_statement = python_grammar.copy() del python_grammar_no_print_statement.keywords["print"] +python_grammar_no_exec_statement = python_grammar.copy() +del python_grammar_no_exec_statement.keywords["exec"] + +python_grammar_no_print_statement_no_exec_statement = python_grammar.copy() +del python_grammar_no_print_statement_no_exec_statement.keywords["print"] +del python_grammar_no_print_statement_no_exec_statement.keywords["exec"] + pattern_grammar = driver.load_packaged_grammar("blib2to3", _PATTERN_GRAMMAR_FILE) pattern_symbols = Symbols(pattern_grammar) diff --git a/tests/function.py b/tests/function.py index 7fa6866..888ef9f 100644 --- a/tests/function.py +++ b/tests/function.py @@ -14,8 +14,9 @@ def func_no_args(): for i in range(10): print(i) continue + exec("new-style exec", {}, {}) return None -async def coroutine(arg): +async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) @@ -93,10 +94,11 @@ def func_no_args(): print(i) continue + exec("new-style exec", {}, {}) return None -async def coroutine(arg): +async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
diff --git a/tests/test_black.py b/tests/test_black.py index 69746d1..3415549 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -180,6 +180,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_python2(self) -> None: + source, expected = read_data('python2') + actual = fs(source) + self.assertFormatEqual(expected, actual) + # black.assert_equivalent(source, actual) + black.assert_stable(source, actual, line_length=ll) + def test_report(self) -> None: report = black.Report() out_lines = []
Expected tree: file_input simple_stmt import_name NAME '#!/usr/bin/env python2\n\n' 'import' NAME ' ' 'sys' /import_name NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME '\n' 'print' RIGHTSHIFT ' ' '>>' power NAME 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"Warning:"' COMMA ',' /testlist_star_expr NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME 'print' RIGHTSHIFT ' ' '>>' power NAME 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"this is a blast from the past."' /testlist_star_expr NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME 'print' RIGHTSHIFT ' ' '>>' power NAME 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"Look, a repr:"' COMMA ',' atom BACKQUOTE ' ' '`' NAME ' ' 'sys' BACKQUOTE ' ' '`' /atom /testlist_star_expr NEWLINE '\n' /simple_stmt funcdef NAME '\n\n' 'def' NAME ' ' 'function' parameters LPAR '(' tfpdef LPAR '(' tfplist NAME '_globals' COMMA ',' NAME ' ' '_locals' /tfplist RPAR ')' /tfpdef RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt exec_stmt NAME 'exec' STRING ' ' '"print \'hi from exec!\'"' NAME ' ' 'in' NAME ' ' '_globals' COMMA ',' NAME ' ' '_locals' /exec_stmt NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef simple_stmt power NAME '\n\n' 'function' trailer LPAR '(' atom LPAR '(' testlist_gexp power NAME 'globals' trailer LPAR '(' RPAR ')' /trailer /power COMMA ',' power NAME ' ' 'locals' trailer LPAR '(' RPAR ')' /trailer /power /testlist_gexp RPAR ')' /atom RPAR ')' /trailer /power NEWLINE '\n' /simple_stmt ENDMARKER '' /file_input Actual tree: file_input simple_stmt import_name NAME '#!/usr/bin/env python2\n\n' 'import' NAME ' ' 'sys' /import_name NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME '\n' 'print' RIGHTSHIFT ' ' '>>' power NAME ' ' 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"Warning:"' COMMA ',' /testlist_star_expr NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME 'print' RIGHTSHIFT ' ' '>>' power NAME ' ' 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"this is a blast from the past."' /testlist_star_expr NEWLINE '\n' /simple_stmt simple_stmt testlist_star_expr shift_expr NAME 'print' RIGHTSHIFT ' ' '>>' power NAME ' ' 'sys' trailer DOT '.' NAME 'stderr' /trailer /power /shift_expr COMMA ',' STRING ' ' '"Look, a repr:"' COMMA ',' atom BACKQUOTE ' ' '`' NAME ' ' 'sys' BACKQUOTE ' ' '`' /atom /testlist_star_expr NEWLINE '\n' /simple_stmt funcdef NAME '\n\n' 'def' NAME ' ' 'function' parameters LPAR '(' tfpdef LPAR '(' tfplist NAME '_globals' COMMA ',' NAME ' ' '_locals' /tfplist RPAR ')' /tfpdef RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt exec_stmt NAME 'exec' STRING ' ' '"print \'hi from exec!\'"' NAME ' ' 'in' NAME ' ' '_globals' COMMA ',' NAME ' ' '_locals' /exec_stmt NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef simple_stmt power NAME '\n\n' 'function' trailer LPAR '(' atom LPAR '(' testlist_gexp power NAME 'globals' trailer LPAR '(' RPAR ')' /trailer /power COMMA ',' power NAME ' ' 'locals' trailer LPAR '(' RPAR ')' /trailer /power /testlist_gexp RPAR ')' /atom RPAR ')' /trailer /power NEWLINE '\n' /simple_stmt ENDMARKER '' /file_input ====================================================================== FAIL: test_python2 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/5619da77e622150490b9375f352afe47/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 187, in test_python2 self.assertFormatEqual(expected, actual) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 67, in assertFormatEqual self.assertEqual(expected, actual) AssertionError: '#!/u[39 chars]nt >>sys.stderr, "Warning:",\nprint >>sys.stde[214 chars]))\n' != '#!/u[39 chars]nt >> sys.stderr, "Warning:",\nprint >> sys.st[217 chars]))\n' #!/usr/bin/env python2 import sys - print >>sys.stderr, "Warning:", + print >> sys.stderr, "Warning:", ? + - print >>sys.stderr, "this is a blast from the past." + print >> sys.stderr, "this is a blast from the past." ? + - print >>sys.stderr, "Look, a repr:", ` sys ` + print >> sys.stderr, "Look, a repr:", ` sys ` ? + def function((_globals, _locals)): exec "print 'hi from exec!'" in _globals, _locals function((globals(), locals())) ---------------------------------------------------------------------- Ran 1 test in 0.024s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_python2
8de552eb4f0fbf1ad84812cde71489cc00d3ed1f
tests/python2.py;tests/test_black.py
psf__black-8
psf/black
diff --git a/black.py b/black.py index dd6e372..9ecfbe1 100644 --- a/black.py +++ b/black.py @@ -2405,10 +2405,17 @@ def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) - # Ensure a trailing comma when expected. + # Ensure a trailing comma for imports, but be careful not to add one after + # any comments. if original.is_import: - if leaves[-1].type != token.COMMA: - leaves.append(Leaf(token.COMMA, ",")) + for i in range(len(leaves) - 1, -1, -1): + if leaves[i].type == STANDALONE_COMMENT: + continue + elif leaves[i].type == token.COMMA: + break + else: + leaves.insert(i + 1, Leaf(token.COMMA, ",")) + break # Populate the line for leaf in leaves: result.append(leaf, preformatted=True)
diff --git a/tests/test_black.py b/tests/test_black.py index 3e0b8a1..86175aa 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -388,6 +388,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_comments7(self) -> None: + source, expected = read_data("comments7") + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) def test_cantfit(self) -> None: source, expected = read_data("cantfit")
Expected tree: file_input simple_stmt import_from NAME 'from' DOT ' ' '.' NAME 'config' NAME ' ' 'import' LPAR ' ' '(' import_as_names NAME '\n ' 'Any' COMMA ',' NAME '\n ' 'Bool' COMMA ',' NAME '\n ' 'ConfigType' COMMA ',' NAME '\n ' 'ConfigTypeAttributes' COMMA ',' NAME '\n ' 'Int' COMMA ',' NAME '\n ' 'Path' COMMA ',' /import_as_names RPAR '\n # String,\n # resolve_to_config_type,\n # DEFAULT_TYPE_ATTRIBUTES,\n' ')' /import_from NEWLINE '\n' /simple_stmt simple_stmt import_from NAME '\n\n' 'from' DOT ' ' '.' NAME 'config' NAME ' ' 'import' LPAR ' ' '(' import_as_names NAME '\n ' 'Any' COMMA ',' NAME '\n ' 'Bool' COMMA ',' NAME '\n ' 'ConfigType' COMMA ',' NAME '\n ' 'ConfigTypeAttributes' COMMA ',' NAME '\n ' 'Int' COMMA ',' NAME '\n ' 'no_comma_here_yet' COMMA ',' /import_as_names RPAR '\n # and some comments,\n # resolve_to_config_type,\n # DEFAULT_TYPE_ATTRIBUTES,\n' ')' /import_from NEWLINE '\n' /simple_stmt ENDMARKER '' /file_input Actual tree: Cannot parse: 11:4: , ====================================================================== FAIL: test_comments7 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/6ba0b304d0c7093a86682761b7bcdeb8/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 395, in test_comments7 self.assertFormatEqual(expected, actual) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 159, in assertFormatEqual self.assertEqual(expected, actual) AssertionError: 'from[181 chars]ES,\n)\n\n\nfrom .config import (\n Any,\n [179 chars]n)\n' != 'from[181 chars]ES,\n ,\n)\n\n\nfrom .config import (\n [192 chars]n)\n' from .config import ( Any, Bool, ConfigType, ConfigTypeAttributes, Int, Path, # String, # resolve_to_config_type, # DEFAULT_TYPE_ATTRIBUTES, + , ) from .config import ( Any, Bool, ConfigType, ConfigTypeAttributes, Int, - no_comma_here_yet, ? - + no_comma_here_yet # and some comments, # resolve_to_config_type, # DEFAULT_TYPE_ATTRIBUTES, + , ) ---------------------------------------------------------------------- Ran 1 test in 0.020s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_comments7
e6ddb68c786256e1cb0c76b42d10c212ef34cb2a
tests/data/comments7.py;tests/test_black.py
psf__black-17
psf/black
diff --git a/black.py b/black.py index 46c0907..c6b018f 100644 --- a/black.py +++ b/black.py @@ -607,6 +607,9 @@ def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: """ srcbuf = io.BytesIO(src) encoding, lines = tokenize.detect_encoding(srcbuf.readline) + if not lines: + return "", encoding, "\n" + newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n" srcbuf.seek(0) with io.TextIOWrapper(srcbuf, encoding) as tiow: @@ -623,7 +626,7 @@ GRAMMARS = [ def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement - if src_txt[-1] != "\n": + if src_txt[-1:] != "\n": src_txt += "\n" for grammar in GRAMMARS: drv = driver.Driver(grammar, pytree.convert)
diff --git a/tests/test_black.py b/tests/test_black.py index f6952c7..e98f019 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -100,6 +100,25 @@ class BlackTestCase(unittest.TestCase): black.err(str(ve)) self.assertEqual(expected, actual) + @patch("black.dump_to_file", dump_to_stderr) + def test_empty(self) -> None: + source = expected = "" + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, line_length=ll) + + def test_empty_ff(self) -> None: + expected = "" + tmp_file = Path(black.dump_to_file()) + try: + self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES)) + with open(tmp_file, encoding="utf8") as f: + actual = f.read() + finally: + os.unlink(tmp_file) + self.assertFormatEqual(expected, actual) + @patch("black.dump_to_file", dump_to_stderr) def test_self(self) -> None: source, expected = read_data("test_black")
====================================================================== ERROR: test_empty (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/000e642a2238316a31276b441184e2a5/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 106, in test_empty actual = fs(source) File "/home/user/BugsInPy/temp/projects/black/black.py", line 577, in format_str src_node = lib2to3_parse(src_contents) File "/home/user/BugsInPy/temp/projects/black/black.py", line 626, in lib2to3_parse if src_txt[-1] != "\n": IndexError: string index out of range ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1)
python -m unittest -q tests.test_black.BlackTestCase.test_empty
bbc09a4f013f2a584f143f3f5e3f76f6082367d4
tests/test_black.py
psf__black-15
psf/black
diff --git a/black.py b/black.py index 7682f7c..7e39c92 100644 --- a/black.py +++ b/black.py @@ -29,7 +29,6 @@ from typing import ( Sequence, Set, Tuple, - Type, TypeVar, Union, cast, @@ -90,34 +89,6 @@ class CannotSplit(Exception): """ -class FormatError(Exception): - """Base exception for `# fmt: on` and `# fmt: off` handling. - - It holds the number of bytes of the prefix consumed before the format - control comment appeared. - """ - - def __init__(self, consumed: int) -> None: - super().__init__(consumed) - self.consumed = consumed - - def trim_prefix(self, leaf: Leaf) -> None: - leaf.prefix = leaf.prefix[self.consumed :] - - def leaf_from_consumed(self, leaf: Leaf) -> Leaf: - """Returns a new Leaf from the consumed part of the prefix.""" - unformatted_prefix = leaf.prefix[: self.consumed] - return Leaf(token.NEWLINE, unformatted_prefix) - - -class FormatOn(FormatError): - """Found a comment like `# fmt: on` in the file.""" - - -class FormatOff(FormatError): - """Found a comment like `# fmt: off` in the file.""" - - class WriteBack(Enum): NO = 0 YES = 1 @@ -759,13 +730,15 @@ class DebugVisitor(Visitor[T]): out(f" {node.value!r}", fg="blue", bold=False) @classmethod - def show(cls, code: str) -> None: + def show(cls, code: Union[str, Leaf, Node]) -> None: """Pretty-print the lib2to3 AST of a given string of `code`. Convenience method for debugging. """ v: DebugVisitor[None] = DebugVisitor() - list(v.visit(lib2to3_parse(code))) + if isinstance(code, str): + code = lib2to3_parse(code) + list(v.visit(code)) KEYWORDS = set(keyword.kwlist) @@ -1306,55 +1279,6 @@ class Line: return bool(self.leaves or self.comments) -class UnformattedLines(Line): - """Just like :class:`Line` but stores lines which aren't reformatted.""" - - def append(self, leaf: Leaf, preformatted: bool = True) -> None: - """Just add a new `leaf` to the end of the lines. - - The `preformatted` argument is ignored. - - Keeps track of indentation `depth`, which is useful when the user - says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`. - """ - try: - list(generate_comments(leaf)) - except FormatOn as f_on: - self.leaves.append(f_on.leaf_from_consumed(leaf)) - raise - - self.leaves.append(leaf) - if leaf.type == token.INDENT: - self.depth += 1 - elif leaf.type == token.DEDENT: - self.depth -= 1 - - def __str__(self) -> str: - """Render unformatted lines from leaves which were added with `append()`. - - `depth` is not used for indentation in this case. - """ - if not self: - return "\n" - - res = "" - for leaf in self.leaves: - res += str(leaf) - return res - - def append_comment(self, comment: Leaf) -> bool: - """Not implemented in this class. Raises `NotImplementedError`.""" - raise NotImplementedError("Unformatted lines don't store comments separately.") - - def maybe_remove_trailing_comma(self, closing: Leaf) -> bool: - """Does nothing and returns False.""" - return False - - def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool: - """Does nothing and returns False.""" - return False - - @dataclass class EmptyLineTracker: """Provides a stateful method that returns the number of potential extra @@ -1376,9 +1300,6 @@ class EmptyLineTracker: This is for separating `def`, `async def` and `class` with extra empty lines (two on module-level). """ - if isinstance(current_line, UnformattedLines): - return 0, 0 - before, after = self._maybe_empty_lines(current_line) before -= self.previous_after self.previous_after = after @@ -1482,7 +1403,7 @@ class LineGenerator(Visitor[Line]): current_line: Line = Factory(Line) remove_u_prefix: bool = False - def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]: + def line(self, indent: int = 0) -> Iterator[Line]: """Generate a line. If the line is empty, only emit if it makes sense. @@ -1491,67 +1412,39 @@ class LineGenerator(Visitor[Line]): If any lines were generated, set up a new current_line. """ if not self.current_line: - if self.current_line.__class__ == type: - self.current_line.depth += indent - else: - self.current_line = type(depth=self.current_line.depth + indent) + self.current_line.depth += indent return # Line is empty, don't emit. Creating a new one unnecessary. complete_line = self.current_line - self.current_line = type(depth=complete_line.depth + indent) + self.current_line = Line(depth=complete_line.depth + indent) yield complete_line - def visit(self, node: LN) -> Iterator[Line]: - """Main method to visit `node` and its children. - - Yields :class:`Line` objects. - """ - if isinstance(self.current_line, UnformattedLines): - # File contained `# fmt: off` - yield from self.visit_unformatted(node) - - else: - yield from super().visit(node) - def visit_default(self, node: LN) -> Iterator[Line]: """Default `visit_*()` implementation. Recurses to children of `node`.""" if isinstance(node, Leaf): any_open_brackets = self.current_line.bracket_tracker.any_open_brackets() - try: - for comment in generate_comments(node): - if any_open_brackets: - # any comment within brackets is subject to splitting - self.current_line.append(comment) - elif comment.type == token.COMMENT: - # regular trailing comment - self.current_line.append(comment) - yield from self.line() - - else: - # regular standalone comment - yield from self.line() - - self.current_line.append(comment) - yield from self.line() - - except FormatOff as f_off: - f_off.trim_prefix(node) - yield from self.line(type=UnformattedLines) - yield from self.visit(node) - - except FormatOn as f_on: - # This only happens here if somebody says "fmt: on" multiple - # times in a row. - f_on.trim_prefix(node) - yield from self.visit_default(node) + for comment in generate_comments(node): + if any_open_brackets: + # any comment within brackets is subject to splitting + self.current_line.append(comment) + elif comment.type == token.COMMENT: + # regular trailing comment + self.current_line.append(comment) + yield from self.line() - else: - normalize_prefix(node, inside_brackets=any_open_brackets) - if self.normalize_strings and node.type == token.STRING: - normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix) - normalize_string_quotes(node) - if node.type not in WHITESPACE: - self.current_line.append(node) + else: + # regular standalone comment + yield from self.line() + + self.current_line.append(comment) + yield from self.line() + + normalize_prefix(node, inside_brackets=any_open_brackets) + if self.normalize_strings and node.type == token.STRING: + normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix) + normalize_string_quotes(node) + if node.type not in WHITESPACE: + self.current_line.append(node) yield from super().visit_default(node) def visit_INDENT(self, node: Node) -> Iterator[Line]: @@ -1648,23 +1541,10 @@ class LineGenerator(Visitor[Line]): yield from self.visit_default(leaf) yield from self.line() - def visit_unformatted(self, node: LN) -> Iterator[Line]: - """Used when file contained a `# fmt: off`.""" - if isinstance(node, Node): - for child in node.children: - yield from self.visit(child) - - else: - try: - self.current_line.append(node) - except FormatOn as f_on: - f_on.trim_prefix(node) - yield from self.line() - yield from self.visit(node) - - if node.type == token.ENDMARKER: - # somebody decided not to put a final `# fmt: on` - yield from self.line() + def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]: + if not self.current_line.bracket_tracker.any_open_brackets(): + yield from self.line() + yield from self.visit_default(leaf) def __attrs_post_init__(self) -> None: """You are in a twisty little maze of passages.""" @@ -1969,6 +1849,9 @@ def container_of(leaf: Leaf) -> LN: if parent.children[0].prefix != same_prefix: break + if parent.type == syms.file_input: + break + if parent.type in SURROUNDED_BY_BRACKETS: break @@ -2106,16 +1989,6 @@ def generate_comments(leaf: LN) -> Iterator[Leaf]: """ for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER): yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines) - if pc.value in FMT_ON: - raise FormatOn(pc.consumed) - - if pc.value in FMT_OFF: - if pc.type == STANDALONE_COMMENT: - raise FormatOff(pc.consumed) - - prev = preceding_leaf(leaf) - if not prev or prev.type in WHITESPACE: # standalone comment in disguise - raise FormatOff(pc.consumed) @dataclass @@ -2188,7 +2061,7 @@ 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) or line.is_comment: + if line.is_comment: yield line return @@ -2680,28 +2553,29 @@ def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None: def normalize_fmt_off(node: Node) -> None: - """Allow `# fmt: off`/`# fmt: on` within bracket pairs. - - Ignores `# fmt: off` and `# fmt: on` outside of brackets. - - Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# fmt: off` - given inside brackets. - """ + """Convert content between `# fmt: off`/`# fmt: on` into standalone comments.""" try_again = True while try_again: - try_again = hide_fmt_off(node) + try_again = convert_one_fmt_off_pair(node) -def hide_fmt_off(node: Node) -> bool: - bt = BracketTracker() - for leaf in node.leaves(): - bt.mark(leaf) - if bt.depth == 0: - continue +def convert_one_fmt_off_pair(node: Node) -> bool: + """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment. + Returns True if a pair was converted. + """ + for leaf in node.leaves(): previous_consumed = 0 for comment in list_comments(leaf.prefix, is_endmarker=False): if comment.value in FMT_OFF: + # We only want standalone comments. If there's no previous leaf or + # the previous leaf is indentation, it's a standalone comment in + # disguise. + if comment.type != STANDALONE_COMMENT: + prev = preceding_leaf(leaf) + if prev and prev.type not in WHITESPACE: + continue + ignored_nodes = list(generate_ignored_nodes(leaf)) first = ignored_nodes[0] # Can be a container node with the `leaf`. parent = first.parent @@ -2710,6 +2584,10 @@ def hide_fmt_off(node: Node) -> bool: hidden_value = ( comment.value + "\n" + "".join(str(n) for n in ignored_nodes) ) + if hidden_value.endswith("\n"): + # That happens when one of the `ignored_nodes` ended with a NEWLINE + # leaf (possibly followed by a DEDENT). + hidden_value = hidden_value[:-1] first_idx = None for ignored in ignored_nodes: index = ignored.remove() @@ -2733,8 +2611,12 @@ def hide_fmt_off(node: Node) -> bool: def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: + """Starting from the container of `leaf`, generate all leaves until `# fmt: on`. + + Stops at the end of the block. + """ container: Optional[LN] = container_of(leaf) - while container is not None: + while container is not None and container.type != token.ENDMARKER: for comment in list_comments(container.prefix, is_endmarker=False): if comment.value in FMT_ON: return
diff --git a/tests/test_black.py b/tests/test_black.py index 3418df9..6638dc4 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -400,6 +400,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_fmtonoff2(self) -> None: + source, expected = read_data("fmtonoff2") + 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_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_parentheses")
Expected tree: file_input simple_stmt import_name NAME 'import' NAME ' ' 'pytest' /import_name NEWLINE '\n' /simple_stmt simple_stmt expr_stmt NAME '\n' 'TmSt' EQUAL ' ' '=' NUMBER ' ' '1' /expr_stmt NEWLINE '\n' /simple_stmt simple_stmt expr_stmt NAME 'TmEx' EQUAL ' ' '=' NUMBER ' ' '2' /expr_stmt NEWLINE '\n' /simple_stmt decorated decorator AT '\n# fmt: off\n\n# Test data:\n# Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]]\n\n' '@' dotted_name NAME 'pytest' DOT '.' NAME 'mark' DOT '.' NAME 'parametrize' /dotted_name LPAR '(' arglist STRING "'test'" COMMA ',' atom LSQB ' ' '[' listmaker atom LSQB "\n\n # Test don't manage the volume\n " '[' atom LPAR '\n ' '(' testlist_gexp STRING "'stuff'" COMMA ',' STRING ' ' "'in'" /testlist_gexp RPAR ')' /atom RSQB '\n ' ']' /atom COMMA ',' /listmaker RSQB '\n' ']' /atom /arglist RPAR ')' NEWLINE '\n' /decorator funcdef NAME 'def' NAME ' ' 'test_fader' parameters LPAR '(' NAME 'test' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt NAME 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef /decorated funcdef NAME '\n' 'def' NAME ' ' 'check_fader' parameters LPAR '(' NAME 'test' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt NAME 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n' 'def' NAME ' ' 'test_calculate_fades' parameters LPAR '(' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt expr_stmt NAME 'calcs' EQUAL ' ' '=' atom LSQB ' ' '[' listmaker atom LPAR '\n # one is zero/none\n ' '(' testlist_gexp NUMBER '0' COMMA ',' NUMBER ' ' '4' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '10' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '6' COMMA ',' NUMBER ' ' '10' /testlist_gexp RPAR ')' /atom COMMA ',' atom LPAR '\n ' '(' testlist_gexp NAME 'None' COMMA ',' NUMBER ' ' '4' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '10' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '6' COMMA ',' NUMBER ' ' '10' /testlist_gexp RPAR ')' /atom COMMA ',' /listmaker RSQB '\n ' ']' /atom /expr_stmt NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef ENDMARKER '\n# fmt: on\n' '' /file_input Actual tree: file_input simple_stmt import_name NAME 'import' NAME ' ' 'pytest' /import_name NEWLINE '\n' /simple_stmt simple_stmt expr_stmt NAME '\n' 'TmSt' EQUAL ' ' '=' NUMBER ' ' '1' /expr_stmt NEWLINE '\n' /simple_stmt simple_stmt expr_stmt NAME 'TmEx' EQUAL ' ' '=' NUMBER ' ' '2' /expr_stmt NEWLINE '\n' /simple_stmt decorated decorator AT '\n# fmt: off\n\n# Test data:\n# Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]]\n\n' '@' dotted_name NAME 'pytest' DOT '.' NAME 'mark' DOT '.' NAME 'parametrize' /dotted_name LPAR '(' arglist STRING "'test'" COMMA ',' atom LSQB ' ' '[' listmaker atom LSQB "\n\n # Test don't manage the volume\n " '[' atom LPAR '\n ' '(' testlist_gexp STRING "'stuff'" COMMA ',' STRING ' ' "'in'" /testlist_gexp RPAR ')' /atom RSQB '\n ' ']' /atom COMMA ',' /listmaker RSQB '\n' ']' /atom /arglist RPAR ')' NEWLINE '\n' /decorator funcdef NAME 'def' NAME ' ' 'test_fader' parameters LPAR '(' NAME 'test' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt NAME 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef /decorated funcdef NAME '\n\n' 'def' NAME ' ' 'check_fader' parameters LPAR '(' NAME 'test' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt NAME 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'test_calculate_fades' parameters LPAR '(' RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT ' ' simple_stmt expr_stmt NAME 'calcs' EQUAL ' ' '=' atom LSQB ' ' '[' listmaker atom LPAR '\n # one is zero/none\n ' '(' testlist_gexp NUMBER '0' COMMA ',' NUMBER ' ' '4' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '10' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '6' COMMA ',' NUMBER ' ' '10' /testlist_gexp RPAR ')' /atom COMMA ',' atom LPAR '\n ' '(' testlist_gexp NAME 'None' COMMA ',' NUMBER ' ' '4' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '10' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '0' COMMA ',' NUMBER ' ' '6' COMMA ',' NUMBER ' ' '10' /testlist_gexp RPAR ')' /atom COMMA ',' /listmaker RSQB '\n ' ']' /atom /expr_stmt NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef ENDMARKER '\n\n# fmt: on\n' '' /file_input ====================================================================== FAIL: test_fmtonoff2 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/6741dac5d765976207f88b8af094fa3c/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 407, in test_fmtonoff2 self.assertFormatEqual(expected, actual) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 122, in assertFormatEqual self.assertEqual(expected, actual) AssertionError: "impo[277 chars]s\n\ndef check_fader(test):\n pass\n\ndef t[177 chars]on\n" != "impo[277 chars]s\n\n\ndef check_fader(test):\n pass\n\n\nd[172 chars]on\n" import pytest TmSt = 1 TmEx = 2 # fmt: off # Test data: # Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]] @pytest.mark.parametrize('test', [ # Test don't manage the volume [ ('stuff', 'in') ], ]) def test_fader(test): pass + def check_fader(test): pass + def test_calculate_fades(): calcs = [ # one is zero/none - (0, 4, 0, 0, 10, 0, 0, 6, 10), ? ------- + (0, 4, 0, 0, 10, 0, 0, 6, 10), - (None, 4, 0, 0, 10, 0, 0, 6, 10), ? ---- + (None, 4, 0, 0, 10, 0, 0, 6, 10), ] + # fmt: on ---------------------------------------------------------------------- Ran 1 test in 0.036s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2
8a8c58252cc023ae250d6febd24f50a8166450d4
tests/data/fmtonoff2.py;tests/test_black.py
psf__black-11
psf/black
diff --git a/black.py b/black.py index 52c5b0c..fb8e474 100644 --- a/black.py +++ b/black.py @@ -2112,8 +2112,19 @@ def split_line( return line_str = str(line).strip("\n") - if not line.should_explode and is_line_short_enough( - line, line_length=line_length, line_str=line_str + + # we don't want to split special comments like type annotations + # https://github.com/python/typing/issues/186 + has_special_comment = False + for leaf in line.leaves: + for comment in line.comments_after(leaf): + if leaf.type == token.COMMA and is_special_comment(comment): + has_special_comment = True + + if ( + not has_special_comment + and not line.should_explode + and is_line_short_enough(line, line_length=line_length, line_str=line_str) ): yield line return @@ -2462,6 +2473,16 @@ def is_import(leaf: Leaf) -> bool: ) +def is_special_comment(leaf: Leaf) -> bool: + """Return True if the given leaf is a special comment. + Only returns true for type comments for now.""" + t = leaf.type + v = leaf.value + return bool( + (t == token.COMMENT or t == STANDALONE_COMMENT) and (v.startswith("# type:")) + ) + + def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None: """Leave existing extra newlines if not `inside_brackets`. Remove everything else. @@ -2951,6 +2972,7 @@ def ensure_visible(leaf: Leaf) -> None: def should_explode(line: Line, opening_bracket: Leaf) -> bool: """Should `line` immediately be split with `delimiter_split()` after RHS?""" + if not ( opening_bracket.parent and opening_bracket.parent.type in {syms.atom, syms.import_from}
diff --git a/tests/test_black.py b/tests/test_black.py index 1d759f2..078e8d8 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -362,6 +362,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_comments6(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) + @patch("black.dump_to_file", dump_to_stderr) def test_cantfit(self) -> None: source, expected = read_data("cantfit")
Expected tree: file_input simple_stmt import_from NAME 'from' NAME ' ' 'typing' NAME ' ' 'import' import_as_names NAME ' ' 'Any' COMMA ',' NAME ' ' 'Tuple' /import_as_names /import_from NEWLINE '\n' /simple_stmt funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'a' COMMA ',' /typedargslist RPAR ' # type: int\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n# test type comments\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME 'a' COMMA ',' NAME ' ' 'b' COMMA ',' NAME ' ' 'c' COMMA ',' NAME ' ' 'd' COMMA ',' NAME ' ' 'e' COMMA ',' NAME ' ' 'f' COMMA ',' NAME ' ' 'g' COMMA ',' NAME ' ' 'h' COMMA ',' NAME ' ' 'i' /typedargslist RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (int, int, int, int, int, int, int, int, int) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'a' COMMA ',' NAME ' # type: int\n ' 'b' COMMA ',' NAME ' # type: int\n ' 'c' COMMA ',' NAME ' # type: int\n ' 'd' COMMA ',' NAME ' # type: int\n ' 'e' COMMA ',' NAME ' # type: int\n ' 'f' COMMA ',' NAME ' # type: int\n ' 'g' COMMA ',' NAME ' # type: int\n ' 'h' COMMA ',' NAME ' # type: int\n ' 'i' COMMA ',' /typedargslist RPAR ' # type: int\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (...) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'arg' COMMA ',' STAR ' # type: int\n ' '*' NAME 'args' COMMA ',' NAME ' # type: *Any\n ' 'default' EQUAL '=' NAME 'False' COMMA ',' DOUBLESTAR ' # type: bool\n ' '**' NAME 'kwargs' COMMA ',' /typedargslist RPAR ' # type: **Any\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (...) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'a' COMMA ',' NAME ' # type: int\n ' 'b' COMMA ',' NAME ' # type: int\n ' 'c' COMMA ',' NAME ' # type: int\n ' 'd' COMMA ',' /typedargslist RPAR ' # type: int\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt expr_stmt NAME ' # type: (...) -> None\n\n ' 'element' EQUAL ' ' '=' NUMBER ' ' '0' /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_element' EQUAL ' ' '=' NUMBER ' ' '1' /expr_stmt NEWLINE ' # type: float' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_element_with_long_name' EQUAL ' ' '=' NUMBER ' ' '2' /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style' EQUAL ' ' '=' atom LPAR ' ' '(' NUMBER '\n ' '3' RPAR '\n ' ')' /atom /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME '\n ' 'tup' EQUAL ' ' '=' atom LPAR ' ' '(' testlist_gexp NAME '\n ' 'another_element' COMMA ',' NAME ' # type: int\n ' 'another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style' COMMA ',' /testlist_gexp RPAR ' # type: int\n ' ')' /atom /expr_stmt NEWLINE ' # type: Tuple[int, int]' '\n' /simple_stmt simple_stmt expr_stmt NAME '\n ' 'a' EQUAL ' ' '=' atom LPAR ' ' '(' arith_expr NAME '\n ' 'element' PLUS '\n ' '+' NAME ' ' 'another_element' PLUS '\n ' '+' NAME ' ' 'another_element_with_long_name' PLUS '\n ' '+' NAME ' ' 'element' PLUS '\n ' '+' NAME ' ' 'another_element' PLUS '\n ' '+' NAME ' ' 'another_element_with_long_name' /arith_expr RPAR '\n ' ')' /atom /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt DEDENT '' /suite /funcdef ENDMARKER '' /file_input Actual tree: file_input simple_stmt import_from NAME 'from' NAME ' ' 'typing' NAME ' ' 'import' import_as_names NAME ' ' 'Any' COMMA ',' NAME ' ' 'Tuple' /import_as_names /import_from NEWLINE '\n' /simple_stmt funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME 'a' COMMA ',' /typedargslist RPAR ')' /parameters COLON ':' suite NEWLINE ' # type: int' '\n' INDENT '' simple_stmt NAME ' ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n# test type comments\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME 'a' COMMA ',' NAME ' ' 'b' COMMA ',' NAME ' ' 'c' COMMA ',' NAME ' ' 'd' COMMA ',' NAME ' ' 'e' COMMA ',' NAME ' ' 'f' COMMA ',' NAME ' ' 'g' COMMA ',' NAME ' ' 'h' COMMA ',' NAME ' ' 'i' /typedargslist RPAR ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (int, int, int, int, int, int, int, int, int) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'a' COMMA ',' NAME ' # type: int\n ' 'b' COMMA ',' NAME ' # type: int\n ' 'c' COMMA ',' NAME ' # type: int\n ' 'd' COMMA ',' NAME ' # type: int\n ' 'e' COMMA ',' NAME ' # type: int\n ' 'f' COMMA ',' NAME ' # type: int\n ' 'g' COMMA ',' NAME ' # type: int\n ' 'h' COMMA ',' NAME ' # type: int\n ' 'i' COMMA ',' /typedargslist RPAR ' # type: int\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (...) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME '\n ' 'arg' COMMA ',' STAR ' # type: int\n ' '*' NAME 'args' COMMA ',' NAME ' # type: *Any\n ' 'default' EQUAL '=' NAME 'False' COMMA ',' DOUBLESTAR ' # type: bool\n ' '**' NAME 'kwargs' COMMA ',' /typedargslist RPAR ' # type: **Any\n' ')' /parameters COLON ':' suite NEWLINE '\n' INDENT '' simple_stmt NAME ' # type: (...) -> None\n ' 'pass' NEWLINE '\n' /simple_stmt DEDENT '' /suite /funcdef funcdef NAME '\n\n' 'def' NAME ' ' 'f' parameters LPAR '(' typedargslist NAME 'a' COMMA ',' NAME ' ' 'b' COMMA ',' NAME ' ' 'c' COMMA ',' NAME ' ' 'd' /typedargslist RPAR ')' /parameters COLON ':' suite NEWLINE ' # type: int # type: int # type: int # type: int' '\n' INDENT '' simple_stmt expr_stmt NAME ' # type: (...) -> None\n\n ' 'element' EQUAL ' ' '=' NUMBER ' ' '0' /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_element' EQUAL ' ' '=' NUMBER ' ' '1' /expr_stmt NEWLINE ' # type: float' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_element_with_long_name' EQUAL ' ' '=' NUMBER ' ' '2' /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME ' ' 'another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style' EQUAL ' ' '=' atom LPAR ' ' '(' NUMBER '\n ' '3' RPAR '\n ' ')' /atom /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt simple_stmt expr_stmt NAME '\n ' 'tup' EQUAL ' ' '=' atom LPAR ' ' '(' testlist_gexp NAME '\n ' 'another_element' COMMA ',' NAME ' # type: int\n ' 'another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style' COMMA ',' /testlist_gexp RPAR ' # type: int\n ' ')' /atom /expr_stmt NEWLINE ' # type: Tuple[int, int]' '\n' /simple_stmt simple_stmt expr_stmt NAME '\n ' 'a' EQUAL ' ' '=' atom LPAR ' ' '(' arith_expr NAME '\n ' 'element' PLUS '\n ' '+' NAME ' ' 'another_element' PLUS '\n ' '+' NAME ' ' 'another_element_with_long_name' PLUS '\n ' '+' NAME ' ' 'element' PLUS '\n ' '+' NAME ' ' 'another_element' PLUS '\n ' '+' NAME ' ' 'another_element_with_long_name' /arith_expr RPAR '\n ' ')' /atom /expr_stmt NEWLINE ' # type: int' '\n' /simple_stmt DEDENT '' /suite /funcdef ENDMARKER '' /file_input ====================================================================== FAIL: test_comments6 (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/523f2d89d53ebeb9a9749b027281b908/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 369, in test_comments6 self.assertFormatEqual(expected, actual) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 156, in assertFormatEqual self.assertEqual(expected, actual) AssertionError: 'from[32 chars]ef f(\n a, # type: int\n):\n pass\n\n\n[1362 chars]nt\n' != 'from[32 chars]ef f(a,): # type: int\n pass\n\n\n# test t[1330 chars]nt\n' from typing import Any, Tuple + def f(a,): # type: int - def f( - a, # type: int - ): pass # test type comments def f(a, b, c, d, e, f, g, h, i): # type: (int, int, int, int, int, int, int, int, int) -> None pass def f( a, # type: int b, # type: int c, # type: int d, # type: int e, # type: int f, # type: int g, # type: int h, # type: int i, # type: int ): # type: (...) -> None pass def f( arg, # type: int *args, # type: *Any default=False, # type: bool **kwargs, # type: **Any ): # type: (...) -> None pass + def f(a, b, c, d): # type: int # type: int # type: int # type: int - def f( - a, # type: int - b, # type: int - c, # type: int - d, # type: int - ): # type: (...) -> None element = 0 # type: int another_element = 1 # type: float another_element_with_long_name = 2 # type: int another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style = ( 3 ) # type: int tup = ( another_element, # type: int another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style, # type: int ) # type: Tuple[int, int] a = ( element + another_element + another_element_with_long_name + element + another_element + another_element_with_long_name ) # type: int ---------------------------------------------------------------------- Ran 1 test in 0.087s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_comments6
283a5d53a8d57e8e186a08c9fbf249e1fbe7bc94
tests/data/comments6.py;tests/test_black.py
psf__black-20
psf/black
diff --git a/black.py b/black.py index dd2e2d1..eafc9e7 100644 --- a/black.py +++ b/black.py @@ -341,8 +341,8 @@ def format_file_in_place( with open(src, "w", encoding=src_buffer.encoding) as f: f.write(dst_contents) elif write_back == write_back.DIFF: - src_name = f"{src.name} (original)" - dst_name = f"{src.name} (formatted)" + src_name = f"{src} (original)" + dst_name = f"{src} (formatted)" diff_contents = diff(src_contents, dst_contents, src_name, dst_name) if lock: lock.acquire()
diff --git a/tests/test_black.py b/tests/test_black.py index ba834c5..6f0ffa3 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -200,7 +200,7 @@ class BlackTestCase(unittest.TestCase): self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) actual = sys.stdout.read() - actual = actual.replace(tmp_file.name, "<stdin>") + actual = actual.replace(str(tmp_file), "<stdin>") finally: sys.stdout = hold_stdout os.unlink(tmp_file)
====================================================================== FAIL: test_expression_diff (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 215, in test_expression_diff self.assertEqual(expected, actual, msg) AssertionError: '--- <stdin> (original)\n+++ <stdin> (format[9503 chars]ER\n' != '--- blk_hz5wmere.log (original)\n+++ blk_hz5[9521 chars]ER\n' - --- <stdin> (original) - +++ <stdin> (formatted) + --- blk_hz5wmere.log (original) + +++ blk_hz5wmere.log (formatted) @@ -1,8 +1,8 @@ ... -'some_string' -b'\\xa3' +"some_string" +b"\\xa3" Name None True False 1 @@ -29,60 +29,78 @@ ~great +value -1 ~int and not v1 ^ 123 + v2 | True (~int) and (not ((v1 ^ (123 + v2)) | True)) -flags & ~ select.EPOLLIN and waiters.write_task is not None +flags & ~select.EPOLLIN and waiters.write_task is not None lambda arg: None lambda a=True: a lambda a, b, c=True: a -lambda a, b, c=True, *, d=(1 << v2), e='str': a -lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b -foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id]) +lambda a, b, c=True, *, d=(1 << v2), e="str": a +lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b +foo = ( + lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[ + port_id + ] +) 1 if True else 2 str or None if True else str or bytes or None (str or None) if True else (str or bytes or None) str or None if (1 if True else 2) else str or bytes or None (str or None) if (1 if True else 2) else (str or bytes or None) -{'2.7': dead, '3.7': (long_live or die_hard)} -{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} +{"2.7": dead, "3.7": (long_live or die_hard)} +{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}} {**a, **b, **c} -{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} -({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None +{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")} +({"a": "b"}, (True or False), (+value), "string", b"bytes") or None () (1,) (1, 2) (1, 2, 3) [] [1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] -[1, 2, 3,] +[1, 2, 3] [*a] [*range(10)] -[*a, 4, 5,] -[4, *a, 5,] -[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more] +[*a, 4, 5] +[4, *a, 5] +[ + this_is_a_very_long_variable_which_will_force_a_delimiter_split, + element, + another, + *more, +] {i for i in (1, 2, 3)} {(i ** 2) for i in (1, 2, 3)} -{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} +{(i ** 2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))} {((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} [i for i in (1, 2, 3)] [(i ** 2) for i in (1, 2, 3)] -[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] +[(i ** 2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))] [((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] {i: 0 for i in (1, 2, 3)} -{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} +{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))} {a: b * 2 for a, b in dictionary.items()} {a: b * -2 for a, b in dictionary.items()} -{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} +{ + k: v + for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension +} Python3 > Python2 > COBOL Life is Life call() call(arg) -call(kwarg='hey') -call(arg, kwarg='hey') -call(arg, another, kwarg='hey', **kwargs) -call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6 +call(kwarg="hey") +call(arg, kwarg="hey") +call(arg, another, kwarg="hey", **kwargs) +call( + this_is_a_very_long_variable_which_will_force_a_delimiter_split, + arg, + another, + kwarg="hey", + **kwargs +) # note: no trailing comma pre-3.6 call(*gidgets[:2]) call(a, *gidgets[:2]) call(**self.screen_kwargs) call(b, **self.screen_kwargs) lukasz.langa.pl @@ -91,11 +109,11 @@ 1.0 .real ....__class__ list[str] dict[str, int] tuple[str, ...] -tuple[str, int, float, dict[str, int],] +tuple[str, int, float, dict[str, int]] very_long_variable_name_filters: t.List[ t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], ] slice[0] slice[0:1] @@ -122,88 +140,122 @@ numpy[-(c + 1):, d] numpy[:, l[-2]] numpy[:, ::-1] numpy[np.newaxis, :] (str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) -{'2.7': dead, '3.7': long_live or die_hard} -{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} +{"2.7": dead, "3.7": long_live or die_hard} +{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"} [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] (SomeName) SomeName (Good, Bad, Ugly) (i for i in (1, 2, 3)) ((i ** 2) for i in (1, 2, 3)) -((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) +((i ** 2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))) (((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) (*starred) -{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs} +{ + "id": "1", + "type": "type", + "started_at": now(), + "ended_at": now() + timedelta(days=10), + "priority": 1, + "import_session_id": 1, + **kwargs, +} a = (1,) b = 1, c = 1 d = (1,) + a + (2,) e = (1,).count(1) -what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove) -what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove) -result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc(),).all() +what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( + vars_to_remove +) +what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( + vars_to_remove +) +result = session.query(models.Customer.id).filter( + models.Customer.account_id == account_id, models.Customer.email == email_address +).order_by( + models.Customer.id.asc() +).all() Ø = set() authors.łukasz.say_thanks() mapping = { A: 0.25 * (10.0 / 12), B: 0.1 * (10.0 / 12), C: 0.1 * (10.0 / 12), D: 0.1 * (10.0 / 12), } + def gen(): yield from outside_of_generator + a = (yield) + async def f(): await some.complicated[0].call(with_args=(True or (1 is not 1))) -print(* [] or [1]) + + +print(*[] or [1]) print(**{1: 3} if False else {x: x for x in range(3)}) -print(* lambda x: x) -for x, in (1,), (2,), (3,): ... -for y in (): ... -for z in (i for i in (1, 2, 3)): ... -for i in (call()): ... -for j in (1 + (2 + 3)): ... -while(this and that): ... -if ( - threading.current_thread() != threading.main_thread() and - threading.current_thread() != threading.main_thread() or - signal.getsignal(signal.SIGINT) != signal.default_int_handler -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa & - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa / - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True +print(*lambda x: x) +for (x,) in (1,), (2,), (3,): + ... +for y in (): + ... +for z in (i for i in (1, 2, 3)): + ... +for i in call(): + ... +for j in 1 + (2 + 3): + ... +while this and that: + ... +if ( + threading.current_thread() != threading.main_thread() + and threading.current_thread() != threading.main_thread() + or signal.getsignal(signal.SIGINT) != signal.default_int_handler +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + +if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): + return True + last_call() # standalone comment at ENDMARKER : Expected diff isn't equal to the actual. If you made changes to expression.py and this is an anticipated difference, overwrite tests/expression.diff with /tmp/blk_046rboir.log ---------------------------------------------------------------------- Ran 1 test in 0.128s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_expression_diff
2e52a2b3ecc0fe025439c3db05a4457ab14f167b
tests/test_black.py
psf__black-18
psf/black
diff --git a/black.py b/black.py index e59a1e5..36e49b0 100644 --- a/black.py +++ b/black.py @@ -4,6 +4,7 @@ from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from enum import Enum, Flag from functools import partial, wraps +import io import keyword import logging from multiprocessing import Manager @@ -465,8 +466,9 @@ def format_file_in_place( """ if src.suffix == ".pyi": mode |= FileMode.PYI - with tokenize.open(src) as src_buffer: - src_contents = src_buffer.read() + + with open(src, "rb") as buf: + newline, encoding, src_contents = prepare_input(buf.read()) try: dst_contents = format_file_contents( src_contents, line_length=line_length, fast=fast, mode=mode @@ -475,7 +477,7 @@ def format_file_in_place( return False if write_back == write_back.YES: - with open(src, "w", encoding=src_buffer.encoding) as f: + with open(src, "w", encoding=encoding, newline=newline) as f: f.write(dst_contents) elif write_back == write_back.DIFF: src_name = f"{src} (original)" @@ -484,7 +486,14 @@ def format_file_in_place( if lock: lock.acquire() try: - sys.stdout.write(diff_contents) + f = io.TextIOWrapper( + sys.stdout.buffer, + encoding=encoding, + newline=newline, + write_through=True, + ) + f.write(diff_contents) + f.detach() finally: if lock: lock.release() @@ -503,7 +512,7 @@ def format_stdin_to_stdout( `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to :func:`format_file_contents`. """ - src = sys.stdin.read() + newline, encoding, src = prepare_input(sys.stdin.buffer.read()) dst = src try: dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode) @@ -514,11 +523,25 @@ def format_stdin_to_stdout( finally: if write_back == WriteBack.YES: - sys.stdout.write(dst) + f = io.TextIOWrapper( + sys.stdout.buffer, + encoding=encoding, + newline=newline, + write_through=True, + ) + f.write(dst) + f.detach() elif write_back == WriteBack.DIFF: src_name = "<stdin> (original)" dst_name = "<stdin> (formatted)" - sys.stdout.write(diff(src, dst, src_name, dst_name)) + f = io.TextIOWrapper( + sys.stdout.buffer, + encoding=encoding, + newline=newline, + write_through=True, + ) + f.write(diff(src, dst, src_name, dst_name)) + f.detach() def format_file_contents( @@ -579,6 +602,19 @@ def format_str( return dst_contents +def prepare_input(src: bytes) -> Tuple[str, str, str]: + """Analyze `src` and return a tuple of (newline, encoding, decoded_contents) + + Where `newline` is either CRLF or LF, and `decoded_contents` is decoded with + universal newlines (i.e. only LF). + """ + srcbuf = io.BytesIO(src) + encoding, lines = tokenize.detect_encoding(srcbuf.readline) + newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n" + srcbuf.seek(0) + return newline, encoding, io.TextIOWrapper(srcbuf, encoding).read() + + GRAMMARS = [ pygram.python_grammar_no_print_statement_no_exec_statement, pygram.python_grammar_no_print_statement, @@ -590,8 +626,7 @@ def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement if src_txt[-1] != "\n": - nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n" - src_txt += nl + src_txt += "\n" for grammar in GRAMMARS: drv = driver.Driver(grammar, pytree.convert) try:
diff --git a/tests/test_black.py b/tests/test_black.py index adf5ede..1f93e6a 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -3,7 +3,7 @@ import asyncio from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from functools import partial -from io import StringIO +from io import BytesIO, TextIOWrapper import os from pathlib import Path import sys @@ -121,8 +121,9 @@ class BlackTestCase(unittest.TestCase): source, expected = read_data("../black") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: - sys.stdin, sys.stdout = StringIO(source), StringIO() - sys.stdin.name = "<stdin>" + sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8") + sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") + sys.stdin.buffer.name = "<stdin>" # type: ignore black.format_stdin_to_stdout( line_length=ll, fast=True, write_back=black.WriteBack.YES ) @@ -139,8 +140,9 @@ class BlackTestCase(unittest.TestCase): expected, _ = read_data("expression.diff") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: - sys.stdin, sys.stdout = StringIO(source), StringIO() - sys.stdin.name = "<stdin>" + sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8") + sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") + sys.stdin.buffer.name = "<stdin>" # type: ignore black.format_stdin_to_stdout( line_length=ll, fast=True, write_back=black.WriteBack.DIFF ) @@ -204,7 +206,7 @@ class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) hold_stdout = sys.stdout try: - sys.stdout = StringIO() + sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) actual = sys.stdout.read() @@ -1108,6 +1110,18 @@ class BlackTestCase(unittest.TestCase): result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"]) self.assertEqual(result.exit_code, 2) + def test_preserves_line_endings(self) -> None: + with TemporaryDirectory() as workspace: + test_file = Path(workspace) / "test.py" + for nl in ["\n", "\r\n"]: + contents = nl.join(["def f( ):", " pass"]) + test_file.write_bytes(contents.encode()) + ff(test_file, write_back=black.WriteBack.YES) + updated_contents: bytes = test_file.read_bytes() + self.assertIn(nl.encode(), updated_contents) # type: ignore + if nl == "\n": + self.assertNotIn(b"\r\n", updated_contents) # type: ignore + if __name__ == "__main__": unittest.main()
====================================================================== FAIL: test_preserves_line_endings (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 1121, in test_preserves_line_endings self.assertIn(nl.encode(), updated_contents) # type: ignore AssertionError: b'\r\n' not found in b'def f():\n pass\n' ---------------------------------------------------------------------- Ran 1 test in 0.013s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings
dbe26161fa68632d608a440666a0960a32630902
tests/test_black.py
psf__black-14
psf/black
diff --git a/black.py b/black.py index f49e6df..36a180d 100644 --- a/black.py +++ b/black.py @@ -20,6 +20,7 @@ from typing import ( Callable, Collection, Dict, + Generator, Generic, Iterable, Iterator, @@ -2910,7 +2911,23 @@ def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf def get_future_imports(node: Node) -> Set[str]: """Return a set of __future__ imports in the file.""" - imports = set() + imports: Set[str] = set() + + def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]: + for child in children: + if isinstance(child, Leaf): + if child.type == token.NAME: + yield child.value + elif child.type == syms.import_as_name: + orig_name = child.children[0] + assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports" + assert orig_name.type == token.NAME, "Invalid syntax parsing imports" + yield orig_name.value + elif child.type == syms.import_as_names: + yield from get_imports_from_children(child.children) + else: + assert False, "Invalid syntax parsing imports" + for child in node.children: if child.type != syms.simple_stmt: break @@ -2929,15 +2946,7 @@ def get_future_imports(node: Node) -> Set[str]: module_name = first_child.children[1] if not isinstance(module_name, Leaf) or module_name.value != "__future__": break - for import_from_child in first_child.children[3:]: - if isinstance(import_from_child, Leaf): - if import_from_child.type == token.NAME: - imports.add(import_from_child.value) - else: - assert import_from_child.type == syms.import_as_names - for leaf in import_from_child.children: - if isinstance(leaf, Leaf) and leaf.type == token.NAME: - imports.add(leaf.value) + imports |= set(get_imports_from_children(first_child.children[3:])) else: break return imports diff --git a/tests/data/python2_unicode_literals.py b/tests/data/python2_unicode_literals.py index ae27919..2fe7039 100644 --- a/tests/data/python2_unicode_literals.py +++ b/tests/data/python2_unicode_literals.py @@ -1,5 +1,7 @@ #!/usr/bin/env python2 -from __future__ import unicode_literals +from __future__ import unicode_literals as _unicode_literals +from __future__ import absolute_import +from __future__ import print_function as lol, with_function u'hello' U"hello" @@ -9,7 +11,9 @@ Ur"hello" #!/usr/bin/env python2 -from __future__ import unicode_literals +from __future__ import unicode_literals as _unicode_literals +from __future__ import absolute_import +from __future__ import print_function as lol, with_function "hello" "hello"
diff --git a/tests/test_black.py b/tests/test_black.py index 8a37197..cc53aa6 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -735,6 +735,14 @@ class BlackTestCase(unittest.TestCase): self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from some.module import black\n") self.assertEqual(set(), black.get_future_imports(node)) + node = black.lib2to3_parse( + "from __future__ import unicode_literals as _unicode_literals" + ) + self.assertEqual({"unicode_literals"}, black.get_future_imports(node)) + node = black.lib2to3_parse( + "from __future__ import unicode_literals as _lol, print" + ) + self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node)) def test_debug_visitor(self) -> None: source, _ = read_data("debug_visitor.py")
====================================================================== FAIL: test_get_future_imports (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 741, in test_get_future_imports self.assertEqual({"unicode_literals"}, black.get_future_imports(node)) File "/home/user/BugsInPy/temp/projects/black/black.py", line 2937, in get_future_imports assert import_from_child.type == syms.import_as_names AssertionError ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports
3bdd42389128bbbe8b64a8e050563f09bff99979
tests/test_black.py
psf__black-5
psf/black
diff --git a/black.py b/black.py index 635eba2..8318674 100644 --- a/black.py +++ b/black.py @@ -1352,7 +1352,10 @@ class Line: bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 - if leaf.parent and leaf.parent.type == syms.arglist: + if leaf.parent and leaf.parent.type in { + syms.arglist, + syms.typedargslist, + }: commas += 1 break @@ -2488,9 +2491,13 @@ def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) - # Ensure a trailing comma for imports, but be careful not to add one after - # any comments. - if original.is_import: + # Ensure a trailing comma for imports and standalone function arguments, but + # be careful not to add one after any comments. + no_commas = original.is_def and not any( + l.type == token.COMMA for l in leaves + ) + + if original.is_import or no_commas: for i in range(len(leaves) - 1, -1, -1): if leaves[i].type == STANDALONE_COMMENT: continue
diff --git a/tests/test_black.py b/tests/test_black.py index 88c03d0..828b3e4 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -264,6 +264,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_function_trailing_comma(self) -> None: + source, expected = read_data("function_trailing_comma") + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) def test_expression(self) -> None: source, expected = read_data("expression")
====================================================================== ERROR: test_function_trailing_comma (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/ec2960e027b850ea197b3f2b8fc7f7ea/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 269, in test_function_trailing_comma source, expected = read_data("function_trailing_comma") File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 64, in read_data with open(base_dir / name, "r", encoding="utf8") as test: FileNotFoundError: [Errno 2] No such file or directory: '/home/user/BugsInPy/temp/projects/black/tests/data/function_trailing_comma.py' ---------------------------------------------------------------------- Ran 1 test in 0.018s FAILED (errors=1)
python -m unittest -q tests.test_black.BlackTestCase.test_function_trailing_comma
1bbb01b854d168d76ebe4bf78961c2152ae075d9
tests/test_black.py
psf__black-16
psf/black
diff --git a/black.py b/black.py index 9d9bada..e3b3882 100644 --- a/black.py +++ b/black.py @@ -2941,11 +2941,24 @@ def gen_python_files_in_dir( """Generate all files under `path` whose paths are not excluded by the `exclude` regex, but are included by the `include` regex. + Symbolic links pointing outside of the root directory are ignored. + `report` is where output about exclusions goes. """ assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}" for child in path.iterdir(): - normalized_path = "/" + child.resolve().relative_to(root).as_posix() + try: + normalized_path = "/" + child.resolve().relative_to(root).as_posix() + except ValueError: + if child.is_symlink(): + report.path_ignored( + child, + "is a symbolic link that points outside of the root directory", + ) + continue + + raise + if child.is_dir(): normalized_path += "/" exclude_match = exclude.search(normalized_path)
diff --git a/tests/test_black.py b/tests/test_black.py index 84b7a61..3418df9 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -11,7 +11,7 @@ import sys from tempfile import TemporaryDirectory from typing import Any, BinaryIO, Generator, List, Tuple, Iterator import unittest -from unittest.mock import patch +from unittest.mock import patch, MagicMock from click import unstyle from click.testing import CliRunner @@ -1162,6 +1162,49 @@ class BlackTestCase(unittest.TestCase): with self.assertRaises(AssertionError): black.assert_equivalent("{}", "None") + def test_symlink_out_of_root_directory(self) -> None: + # prepare argumens + path = MagicMock() + root = THIS_DIR + child = MagicMock() + include = re.compile(black.DEFAULT_INCLUDES) + exclude = re.compile(black.DEFAULT_EXCLUDES) + report = black.Report() + + # set the behavior of mock arguments + # child should behave like a symlink which resolved path is clearly + # outside of the root directory + path.iterdir.return_value = [child] + child.resolve.return_value = Path("/a/b/c") + child.is_symlink.return_value = True + + # call the method + # it should not raise any error + list(black.gen_python_files_in_dir(path, root, include, exclude, report)) + + # check the call of the methods of the mock objects + path.iterdir.assert_called_once() + child.resolve.assert_called_once() + child.is_symlink.assert_called_once() + + # set the behavior of mock arguments + # child should behave like a strange file which resolved path is clearly + # outside of the root directory + child.is_symlink.return_value = False + + # call the method + # it should raise a ValueError + with self.assertRaises(ValueError): + list(black.gen_python_files_in_dir(path, root, include, exclude, report)) + + # check the call of the methods of the mock objects + path.iterdir.assert_called() + self.assertEqual(path.iterdir.call_count, 2) + child.resolve.assert_called() + self.assertEqual(child.resolve.call_count, 2) + child.is_symlink.assert_called() + self.assertEqual(child.is_symlink.call_count, 2) + if __name__ == "__main__": unittest.main(module="test_black")
====================================================================== ERROR: test_symlink_out_of_root_directory (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 1183, in test_symlink_out_of_root_directory list(black.gen_python_files_in_dir(path, root, include, exclude, report)) File "/home/user/BugsInPy/temp/projects/black/black.py", line 2948, in gen_python_files_in_dir normalized_path = "/" + child.resolve().relative_to(root).as_posix() File "/opt/conda/envs/4bef5a2367b8479c0a0dd52aef5fd46b/lib/python3.8/pathlib.py", line 904, in relative_to raise ValueError("{!r} does not start with {!r}" ValueError: '/a/b/c' does not start with '/home/user/BugsInPy/temp/projects/black/tests' ---------------------------------------------------------------------- Ran 1 test in 0.008s FAILED (errors=1)
python -m unittest -q tests.test_black.BlackTestCase.test_symlink_out_of_root_directory
fb34c9e19589d05f92084a28940837151251ebd6
tests/test_black.py
psf__black-1
psf/black
diff --git a/black.py b/black.py index 2a913fc..fc1597a 100644 --- a/black.py +++ b/black.py @@ -618,7 +618,14 @@ def reformat_many( if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 worker_count = min(worker_count, 61) - executor = ProcessPoolExecutor(max_workers=worker_count) + try: + executor = ProcessPoolExecutor(max_workers=worker_count) + except OSError: + # we arrive here if the underlying system does not support multi-processing + # like in AWS Lambda, in which case we gracefully fallback to the default + # mono-process Executor by using None + executor = None + try: loop.run_until_complete( schedule_formatting( @@ -633,7 +640,8 @@ def reformat_many( ) finally: shutdown(loop) - executor.shutdown() + if executor is not None: + executor.shutdown() async def schedule_formatting( @@ -643,7 +651,7 @@ async def schedule_formatting( mode: Mode, report: "Report", loop: asyncio.AbstractEventLoop, - executor: Executor, + executor: Optional[Executor], ) -> None: """Run formatting of `sources` in parallel using the provided `executor`.
diff --git a/tests/test_black.py b/tests/test_black.py index 11bba1f..a0e57dc 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -1273,6 +1273,27 @@ class BlackTestCase(unittest.TestCase): self.assertIn(one, cache) self.assertIn(two, cache) + @patch("black.ProcessPoolExecutor", autospec=True) + def test_works_in_mono_process_only_environment(self, mock_executor) -> None: + mock_executor.side_effect = OSError() + mode = black.FileMode() + with cache_dir() as workspace: + one = (workspace / "one.py").resolve() + with one.open("w") as fobj: + fobj.write("print('hello')") + two = (workspace / "two.py").resolve() + with two.open("w") as fobj: + fobj.write("print('hello')") + black.write_cache({}, [one], mode) + self.invokeBlack([str(workspace)]) + with one.open("r") as fobj: + self.assertEqual(fobj.read(), "print('hello')") + with two.open("r") as fobj: + self.assertEqual(fobj.read(), 'print("hello")\n') + cache = black.read_cache(mode) + self.assertIn(one, cache) + self.assertIn(two, cache) + def test_no_cache_when_writeback_diff(self) -> None: mode = black.FileMode() with cache_dir() as workspace:
====================================================================== FAIL: test_works_in_mono_process_only_environment (tests.test_black.BlackTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/conda/envs/87b58448f32fe09241efe0a490d468af/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 1288, in test_works_in_mono_process_only_environment self.invokeBlack([str(workspace)]) File "/home/user/BugsInPy/temp/projects/black/tests/test_black.py", line 162, in invokeBlack self.assertEqual(result.exit_code, exit_code, msg=runner.stderr_bytes.decode()) AssertionError: 1 != 0 : ---------------------------------------------------------------------- Ran 1 test in 0.071s FAILED (failures=1)
python -m unittest -q tests.test_black.BlackTestCase.test_works_in_mono_process_only_environment
26c9465a22c732ab1e17b0dec578fa3432e9b558
tests/test_black.py
cookiecutter__cookiecutter-4
cookiecutter/cookiecutter
diff --git a/cookiecutter/exceptions.py b/cookiecutter/exceptions.py index 0ad6b58..415f99e 100755 --- a/cookiecutter/exceptions.py +++ b/cookiecutter/exceptions.py @@ -81,3 +81,9 @@ class InvalidModeException(CookiecutterException): Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time. """ + + +class FailedHookException(CookiecutterException): + """ + Raised when a hook script fails + """ diff --git a/cookiecutter/generate.py b/cookiecutter/generate.py index a38ef26..d69f1de 100755 --- a/cookiecutter/generate.py +++ b/cookiecutter/generate.py @@ -24,11 +24,12 @@ from binaryornot.check import is_binary from .exceptions import ( NonTemplatedInputDirException, ContextDecodingException, + FailedHookException, OutputDirExistsException ) from .find import find_template from .utils import make_sure_path_exists, work_in -from .hooks import run_hook, EXIT_SUCCESS +from .hooks import run_hook def copy_without_render(path, context): @@ -257,7 +258,10 @@ def generate_files(repo_dir, context=None, output_dir='.', # run pre-gen hook from repo_dir with work_in(repo_dir): - if run_hook('pre_gen_project', project_dir, context) != EXIT_SUCCESS: + try: + run_hook('pre_gen_project', project_dir, context) + except FailedHookException: + shutil.rmtree(project_dir, ignore_errors=True) logging.error("Stopping generation because pre_gen_project" " hook script didn't exit sucessfully") return diff --git a/cookiecutter/hooks.py b/cookiecutter/hooks.py index 550d6de..81045d1 100755 --- a/cookiecutter/hooks.py +++ b/cookiecutter/hooks.py @@ -18,6 +18,7 @@ import tempfile from jinja2 import Template from cookiecutter import utils +from .exceptions import FailedHookException _HOOKS = [ @@ -69,7 +70,10 @@ def run_script(script_path, cwd='.'): shell=run_thru_shell, cwd=cwd ) - return proc.wait() + exit_status = proc.wait() + if exit_status != EXIT_SUCCESS: + raise FailedHookException( + "Hook script failed (exit status: %d)" % exit_status) def run_script_with_context(script_path, cwd, context): @@ -91,7 +95,7 @@ def run_script_with_context(script_path, cwd, context): ) as temp: temp.write(Template(contents).render(**context)) - return run_script(temp.name, cwd) + run_script(temp.name, cwd) def run_hook(hook_name, project_dir, context): @@ -105,5 +109,5 @@ def run_hook(hook_name, project_dir, context): script = find_hooks().get(hook_name) if script is None: logging.debug('No hooks found') - return EXIT_SUCCESS - return run_script_with_context(script, project_dir, context) + return + run_script_with_context(script, project_dir, context)
diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 8df394f..e7f7ee1 100755 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -11,8 +11,9 @@ Tests for `cookiecutter.hooks` module. import sys import os import stat +import pytest -from cookiecutter import hooks, utils +from cookiecutter import hooks, utils, exceptions def make_test_repo(name): @@ -166,3 +167,16 @@ class TestExternalHooks(object): hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt')) + + def test_run_failing_hook(self): + hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py') + tests_dir = os.path.join(self.repo_path, 'input{{hooks}}') + + with open(hook_path, 'w') as f: + f.write("#!/usr/bin/env python\n") + f.write("import sys; sys.exit(1)\n") + + with utils.work_in(self.repo_path): + with pytest.raises(exceptions.FailedHookException) as excinfo: + hooks.run_hook('pre_gen_project', tests_dir, {}) + assert 'Hook script failed' in str(excinfo)
GLOB sdist-make: /home/user/BugsInPy/temp/projects/cookiecutter/setup.py py27 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py27 ERROR: InterpreterNotFound: python2.7 py33 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py33 ERROR: InterpreterNotFound: python3.3 py34 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py34 ERROR: InterpreterNotFound: python3.4 py35 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py35 py35 installdeps: pytest, pytest-cov, pytest-mock py35 inst: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.2.1.zip py35 installed: DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality.,attrs==22.1.0,binaryornot==0.4.4,chardet==4.0.0,click==7.1.2,cookiecutter @ file:///home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.2.1.zip,coverage==5.5,future==0.18.3,importlib-metadata==2.1.3,iniconfig==1.1.1,Jinja2==2.11.3,MarkupSafe==1.1.1,packaging==20.9,pathlib2==2.3.7.post1,pluggy==0.13.1,py==1.11.0,pyparsing==2.4.7,pytest==6.1.2,pytest-cov==2.12.1,pytest-mock==3.5.1,ruamel.yaml==0.17.32,ruamel.yaml.clib==0.2.7,six==1.16.0,toml==0.10.2,whichcraft==0.6.1,zipp==1.2.0 py35 run-test-pre: PYTHONHASHSEED='1686038354' py35 run-test: commands[0] | py.test --cov=cookiecutter tests/test_hooks.py::TestExternalHooks::test_run_failing_hook ============================= test session starts ============================== platform linux -- Python 3.5.6, pytest-6.1.2, py-1.11.0, pluggy-0.13.1 cachedir: .tox/py35/.pytest_cache rootdir: /home/user/BugsInPy/temp/projects/cookiecutter plugins: mock-3.5.1, cov-2.12.1 collected 1 item tests/test_hooks.py F [100%] =================================== FAILURES =================================== ___________________ TestExternalHooks.test_run_failing_hook ____________________ self = <tests.test_hooks.TestExternalHooks object at 0x7f2bd7051ac8> def test_run_failing_hook(self): hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py') tests_dir = os.path.join(self.repo_path, 'input{{hooks}}') with open(hook_path, 'w') as f: f.write("#!/usr/bin/env python\n") f.write("import sys; sys.exit(1)\n") with utils.work_in(self.repo_path): > with pytest.raises(exceptions.FailedHookException) as excinfo: E AttributeError: module 'cookiecutter.exceptions' has no attribute 'FailedHookException' tests/test_hooks.py:180: AttributeError ----------- coverage: platform linux, python 3.5.6-final-0 ----------- Name Stmts Miss Cover ------------------------------------------------ cookiecutter/__init__.py 2 0 100% cookiecutter/cli.py 33 33 0% cookiecutter/config.py 31 31 0% cookiecutter/exceptions.py 12 0 100% cookiecutter/find.py 17 17 0% cookiecutter/generate.py 144 144 0% cookiecutter/hooks.py 43 28 35% cookiecutter/main.py 43 43 0% cookiecutter/prompt.py 47 47 0% cookiecutter/replay.py 33 33 0% cookiecutter/utils.py 32 11 66% cookiecutter/vcs.py 52 52 0% ------------------------------------------------ TOTAL 489 439 10% =========================== short test summary info ============================ FAILED tests/test_hooks.py::TestExternalHooks::test_run_failing_hook - Attrib... ============================== 1 failed in 0.11s =============================== ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py35/bin/py.test --cov=cookiecutter tests/test_hooks.py::TestExternalHooks::test_run_failing_hook (exited with code 1) pypy create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/pypy ERROR: InterpreterNotFound: pypy flake8 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/flake8 flake8 installdeps: flake8==2.3.0, pep8==1.6.2 flake8 inst: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.2.1.zip flake8 installed: DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality.,binaryornot==0.4.4,chardet==4.0.0,click==7.1.2,cookiecutter @ file:///home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.2.1.zip,flake8==2.3.0,future==0.18.3,Jinja2==2.11.3,MarkupSafe==1.1.1,mccabe==0.6.1,pep8==1.6.2,pyflakes==2.4.0,ruamel.yaml==0.17.32,ruamel.yaml.clib==0.2.7,whichcraft==0.6.1 flake8 run-test-pre: PYTHONHASHSEED='1686038354' flake8 run-test: commands[0] | flake8 cookiecutter tests setup.py ___________________________________ summary ____________________________________ ERROR: py27: InterpreterNotFound: python2.7 ERROR: py33: InterpreterNotFound: python3.3 ERROR: py34: InterpreterNotFound: python3.4 ERROR: py35: commands failed ERROR: pypy: InterpreterNotFound: pypy flake8: commands succeeded
tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook
9568ab6ecd2d6836646006c59473c4a4ac0dee04
tests/test_hooks.py
cookiecutter__cookiecutter-2
cookiecutter/cookiecutter
diff --git a/cookiecutter/hooks.py b/cookiecutter/hooks.py index 20ccae2..3c73f74 100644 --- a/cookiecutter/hooks.py +++ b/cookiecutter/hooks.py @@ -54,11 +54,14 @@ def find_hook(hook_name, hooks_dir='hooks'): logger.debug('No hooks/dir in template_dir') return None + scripts = [] for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): - return os.path.abspath(os.path.join(hooks_dir, hook_file)) + scripts.append(os.path.abspath(os.path.join(hooks_dir, hook_file))) - return None + if len(scripts) == 0: + return None + return scripts def run_script(script_path, cwd='.'): @@ -119,9 +122,10 @@ def run_hook(hook_name, project_dir, context): :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ - script = find_hook(hook_name) - if script is None: + scripts = find_hook(hook_name) + if not scripts: logger.debug('No %s hook found', hook_name) return logger.debug('Running hook %s', hook_name) - run_script_with_context(script, project_dir, context) + for script in scripts: + run_script_with_context(script, project_dir, context)
diff --git a/tests/test_hooks.py b/tests/test_hooks.py index be4038f..bd374ad 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -9,7 +9,7 @@ import pytest from cookiecutter import hooks, utils, exceptions -def make_test_repo(name): +def make_test_repo(name, multiple_hooks=False): """Create test repository for test setup methods.""" hook_dir = os.path.join(name, 'hooks') template = os.path.join(name, 'input{{hooks}}') @@ -47,6 +47,26 @@ def make_test_repo(name): # Set the execute bit os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) + # Adding an additional pre script + if multiple_hooks: + if sys.platform.startswith('win'): + pre = 'pre_gen_project.bat' + with open(os.path.join(hook_dir, pre), 'w') as f: + f.write("@echo off\n") + f.write("\n") + f.write("echo post generation hook\n") + f.write("echo. >shell_pre.txt\n") + else: + pre = 'pre_gen_project.sh' + filename = os.path.join(hook_dir, pre) + with open(filename, 'w') as f: + f.write("#!/bin/bash\n") + f.write("\n") + f.write("echo 'post generation hook';\n") + f.write("touch 'shell_pre.txt'\n") + # Set the execute bit + os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) + return post @@ -68,11 +88,11 @@ class TestFindHooks(object): with utils.work_in(self.repo_path): expected_pre = os.path.abspath('hooks/pre_gen_project.py') actual_hook_path = hooks.find_hook('pre_gen_project') - assert expected_pre == actual_hook_path + assert expected_pre == actual_hook_path[0] expected_post = os.path.abspath('hooks/{}'.format(self.post_hook)) actual_hook_path = hooks.find_hook('post_gen_project') - assert expected_post == actual_hook_path + assert expected_post == actual_hook_path[0] def test_no_hooks(self): """`find_hooks` should return None if the hook could not be found.""" @@ -98,7 +118,7 @@ class TestExternalHooks(object): def setup_method(self, method): """External hooks related tests setup fixture.""" - self.post_hook = make_test_repo(self.repo_path) + self.post_hook = make_test_repo(self.repo_path, multiple_hooks=True) def teardown_method(self, method): """External hooks related tests teardown fixture.""" @@ -108,6 +128,8 @@ class TestExternalHooks(object): os.remove('python_pre.txt') if os.path.exists('shell_post.txt'): os.remove('shell_post.txt') + if os.path.exists('shell_pre.txt'): + os.remove('shell_pre.txt') if os.path.exists('tests/shell_post.txt'): os.remove('tests/shell_post.txt') if os.path.exists('tests/test-hooks/input{{hooks}}/python_pre.txt'): @@ -163,6 +185,7 @@ class TestExternalHooks(object): with utils.work_in(self.repo_path): hooks.run_hook('pre_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt')) + assert os.path.isfile(os.path.join(tests_dir, 'shell_pre.txt')) hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
0 lint recreate: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint lint installdeps: pre-commit>=1.20.0 lint installed: cfgv==3.3.1,distlib==0.3.6,filelock==3.4.1,identify==2.4.4,importlib-metadata==4.8.3,importlib-resources==5.2.3,nodeenv==1.6.0,platformdirs==2.4.0,pre-commit==2.17.0,PyYAML==6.0,toml==0.10.2,typing-extensions==4.1.1,virtualenv==20.17.1,zipp==3.6.0 lint run-test-pre: PYTHONHASHSEED='1942306892' lint run-test: commands[0] | python -m pre_commit run tests/test_hooks.py::TestFindHooks::test_find_hook [WARNING] Unstaged files detected. [INFO] Stashing unstaged files to /root/.cache/pre-commit/patch1689392265-2582. [INFO] Initializing environment for https://gitlab.com/pycqa/flake8. [INFO] Restored changes from /root/.cache/pre-commit/patch1689392265-2582. An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'fetch', 'origin', '--tags') return code: 128 expected return code: 0 stdout: (none) stderr: fatal: could not read Username for 'https://gitlab.com': No such device or address Check the log at /root/.cache/pre-commit/pre-commit.log ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint/bin/python -m pre_commit run tests/test_hooks.py::TestFindHooks::test_find_hook (exited with code 3) py36 recreate: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36 py36 installdeps: -rtest_requirements.txt py36 installed: attrs==22.2.0,coverage==6.2,freezegun==1.2.2,importlib-metadata==4.8.3,iniconfig==1.1.1,packaging==21.3,pluggy==1.0.0,py==1.11.0,pyparsing==3.1.0,pytest==7.0.1,pytest-cov==4.0.0,pytest-mock==3.6.1,python-dateutil==2.8.2,six==1.16.0,tomli==1.2.3,typing-extensions==4.1.1,zipp==3.6.0 py36 run-test-pre: PYTHONHASHSEED='1942306892' py36 run-test: commands[0] | pip install -e . Obtaining file:///home/user/BugsInPy/temp/projects/cookiecutter Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' Collecting click>=7.0 Using cached click-8.0.4-py3-none-any.whl (97 kB) Collecting poyo>=0.5.0 Using cached poyo-0.5.0-py2.py3-none-any.whl (10 kB) Collecting python-slugify>=4.0.0 Using cached python_slugify-6.1.2-py2.py3-none-any.whl (9.4 kB) Collecting MarkupSafe<2.0.0 Using cached MarkupSafe-1.1.1-cp36-cp36m-manylinux2010_x86_64.whl (32 kB) Collecting requests>=2.23.0 Using cached requests-2.27.1-py2.py3-none-any.whl (63 kB) Collecting binaryornot>=0.4.4 Using cached binaryornot-0.4.4-py2.py3-none-any.whl (9.0 kB) Collecting Jinja2<3.0.0 Using cached Jinja2-2.11.3-py2.py3-none-any.whl (125 kB) Collecting jinja2-time>=0.2.0 Using cached jinja2_time-0.2.0-py2.py3-none-any.whl (6.4 kB) Requirement already satisfied: importlib-metadata; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from click>=7.0->cookiecutter==2.0.0) (4.8.3) Collecting text-unidecode>=1.3 Using cached text_unidecode-1.3-py2.py3-none-any.whl (78 kB) Collecting urllib3<1.27,>=1.21.1 Using cached urllib3-1.26.16-py2.py3-none-any.whl (143 kB) Collecting idna<4,>=2.5; python_version >= "3" Using cached idna-3.4-py3-none-any.whl (61 kB) Collecting certifi>=2017.4.17 Using cached certifi-2023.5.7-py3-none-any.whl (156 kB) Collecting charset-normalizer~=2.0.0; python_version >= "3" Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB) Collecting chardet>=3.0.2 Using cached chardet-5.0.0-py3-none-any.whl (193 kB) Collecting arrow Using cached arrow-1.2.3-py3-none-any.whl (66 kB) Requirement already satisfied: typing-extensions>=3.6.4; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->click>=7.0->cookiecutter==2.0.0) (4.1.1) Requirement already satisfied: zipp>=0.5 in ./.tox/py36/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->click>=7.0->cookiecutter==2.0.0) (3.6.0) Requirement already satisfied: python-dateutil>=2.7.0 in ./.tox/py36/lib/python3.6/site-packages (from arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (2.8.2) Requirement already satisfied: six>=1.5 in ./.tox/py36/lib/python3.6/site-packages (from python-dateutil>=2.7.0->arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (1.16.0) Installing collected packages: click, poyo, text-unidecode, python-slugify, MarkupSafe, urllib3, idna, certifi, charset-normalizer, requests, chardet, binaryornot, Jinja2, arrow, jinja2-time, cookiecutter Running setup.py develop for cookiecutter Successfully installed Jinja2-2.11.3 MarkupSafe-1.1.1 arrow-1.2.3 binaryornot-0.4.4 certifi-2023.5.7 chardet-5.0.0 charset-normalizer-2.0.12 click-8.0.4 cookiecutter idna-3.4 jinja2-time-0.2.0 poyo-0.5.0 python-slugify-6.1.2 requests-2.27.1 text-unidecode-1.3 urllib3-1.26.16 WARNING: You are using pip version 20.1.1; however, version 21.3.1 is available. You should consider upgrading via the '/home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python -m pip install --upgrade pip' command. py36 run-test: commands[1] | pytest --cov=cookiecutter tests/test_hooks.py::TestFindHooks::test_find_hook ============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-7.0.1, pluggy-1.0.0 -- /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python cachedir: .tox/py36/.pytest_cache rootdir: /home/user/BugsInPy/temp/projects/cookiecutter, configfile: setup.cfg plugins: mock-3.6.1, cov-4.0.0 collecting ... collected 1 item tests/test_hooks.py::TestFindHooks::test_find_hook FAILED [100%] =================================== FAILURES =================================== _________________________ TestFindHooks.test_find_hook _________________________ self = <tests.test_hooks.TestFindHooks object at 0x7fb534c6fbe0> def test_find_hook(self): """Finds the specified hook.""" with utils.work_in(self.repo_path): expected_pre = os.path.abspath('hooks/pre_gen_project.py') actual_hook_path = hooks.find_hook('pre_gen_project') > assert expected_pre == actual_hook_path[0] E AssertionError: assert '/home/user/BugsInPy/temp/projects/cookiecutter/tests/test-hooks/hooks/pre_gen_project.py' == '/' E - / E + /home/user/BugsInPy/temp/projects/cookiecutter/tests/test-hooks/hooks/pre_gen_project.py tests/test_hooks.py:91: AssertionError ----------- coverage: platform linux, python 3.6.9-final-0 ----------- Name Stmts Miss Cover Missing ----------------------------------------------------------- cookiecutter/__init__.py 1 0 100% cookiecutter/__main__.py 1 1 0% 2 cookiecutter/cli.py 51 51 0% 2-170 cookiecutter/config.py 53 53 0% 2-124 cookiecutter/environment.py 20 13 35% 23-36, 44-49, 64 cookiecutter/exceptions.py 23 4 83% 120-122, 126 cookiecutter/extensions.py 26 26 0% 2-51 cookiecutter/find.py 17 17 0% 2-31 cookiecutter/generate.py 173 173 0% 2-372 cookiecutter/hooks.py 60 32 47% 54-55, 61, 70-90, 100-111, 122-127 cookiecutter/log.py 21 21 0% 2-51 cookiecutter/main.py 29 29 0% 7-109 cookiecutter/prompt.py 90 75 17% 19, 32, 41, 54-78, 86-96, 107-119, 139-156, 164-168, 177-226 cookiecutter/replay.py 27 27 0% 6-51 cookiecutter/repository.py 39 39 0% 2-127 cookiecutter/utils.py 48 25 48% 21-22, 38-45, 68-69, 84-107 cookiecutter/vcs.py 53 53 0% 2-120 cookiecutter/zipfile.py 56 56 0% 2-112 ----------------------------------------------------------- TOTAL 788 695 12% =========================== short test summary info ============================ FAILED tests/test_hooks.py::TestFindHooks::test_find_hook - AssertionError: a... ============================== 1 failed in 0.68s =============================== ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/pytest --cov=cookiecutter tests/test_hooks.py::TestFindHooks::test_find_hook (exited with code 1) py37 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py37 ERROR: InterpreterNotFound: python3.7 py38 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py38 ERROR: InterpreterNotFound: python3.8 pypy3 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/pypy3 ERROR: InterpreterNotFound: pypy3 ___________________________________ summary ____________________________________ ERROR: lint: commands failed ERROR: py36: commands failed ERROR: py37: InterpreterNotFound: python3.7 ERROR: py38: InterpreterNotFound: python3.8 ERROR: pypy3: InterpreterNotFound: pypy3 RUN EVERY COMMAND 1 tox tests/test_hooks.py::TestFindHooks::test_find_hook lint installed: cfgv==3.3.1,distlib==0.3.6,filelock==3.4.1,identify==2.4.4,importlib-metadata==4.8.3,importlib-resources==5.2.3,nodeenv==1.6.0,platformdirs==2.4.0,pre-commit==2.17.0,PyYAML==6.0,toml==0.10.2,typing-extensions==4.1.1,virtualenv==20.17.1,zipp==3.6.0 lint run-test-pre: PYTHONHASHSEED='2594423239' lint run-test: commands[0] | python -m pre_commit run tests/test_hooks.py::TestExternalHooks::test_run_hook [WARNING] Unstaged files detected. [INFO] Stashing unstaged files to /root/.cache/pre-commit/patch1689392318-2654. [INFO] Initializing environment for https://gitlab.com/pycqa/flake8. [INFO] Restored changes from /root/.cache/pre-commit/patch1689392318-2654. An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'fetch', 'origin', '--tags') return code: 128 expected return code: 0 stdout: (none) stderr: fatal: could not read Username for 'https://gitlab.com': No such device or address Check the log at /root/.cache/pre-commit/pre-commit.log ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint/bin/python -m pre_commit run tests/test_hooks.py::TestExternalHooks::test_run_hook (exited with code 3) py36 installed: arrow==1.2.3,attrs==22.2.0,binaryornot==0.4.4,certifi==2023.5.7,chardet==5.0.0,charset-normalizer==2.0.12,click==8.0.4,-e git+https://github.com/cookiecutter/cookiecutter@d7e7b28811e474e14d1bed747115e47dcdd15ba3#egg=cookiecutter,coverage==6.2,freezegun==1.2.2,idna==3.4,importlib-metadata==4.8.3,iniconfig==1.1.1,Jinja2==2.11.3,jinja2-time==0.2.0,MarkupSafe==1.1.1,packaging==21.3,pluggy==1.0.0,poyo==0.5.0,py==1.11.0,pyparsing==3.1.0,pytest==7.0.1,pytest-cov==4.0.0,pytest-mock==3.6.1,python-dateutil==2.8.2,python-slugify==6.1.2,requests==2.27.1,six==1.16.0,text-unidecode==1.3,tomli==1.2.3,typing-extensions==4.1.1,urllib3==1.26.16,zipp==3.6.0 py36 run-test-pre: PYTHONHASHSEED='2594423239' py36 run-test: commands[0] | pip install -e . Obtaining file:///home/user/BugsInPy/temp/projects/cookiecutter Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' Requirement already satisfied: requests>=2.23.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (2.27.1) Requirement already satisfied: Jinja2<3.0.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (2.11.3) Requirement already satisfied: click>=7.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (8.0.4) Requirement already satisfied: binaryornot>=0.4.4 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (0.4.4) Requirement already satisfied: poyo>=0.5.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (0.5.0) Requirement already satisfied: MarkupSafe<2.0.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (1.1.1) Requirement already satisfied: python-slugify>=4.0.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (6.1.2) Requirement already satisfied: jinja2-time>=0.2.0 in ./.tox/py36/lib/python3.6/site-packages (from cookiecutter==2.0.0) (0.2.0) Requirement already satisfied: charset-normalizer~=2.0.0; python_version >= "3" in ./.tox/py36/lib/python3.6/site-packages (from requests>=2.23.0->cookiecutter==2.0.0) (2.0.12) Requirement already satisfied: idna<4,>=2.5; python_version >= "3" in ./.tox/py36/lib/python3.6/site-packages (from requests>=2.23.0->cookiecutter==2.0.0) (3.4) Requirement already satisfied: certifi>=2017.4.17 in ./.tox/py36/lib/python3.6/site-packages (from requests>=2.23.0->cookiecutter==2.0.0) (2023.5.7) Requirement already satisfied: urllib3<1.27,>=1.21.1 in ./.tox/py36/lib/python3.6/site-packages (from requests>=2.23.0->cookiecutter==2.0.0) (1.26.16) Requirement already satisfied: importlib-metadata; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from click>=7.0->cookiecutter==2.0.0) (4.8.3) Requirement already satisfied: chardet>=3.0.2 in ./.tox/py36/lib/python3.6/site-packages (from binaryornot>=0.4.4->cookiecutter==2.0.0) (5.0.0) Requirement already satisfied: text-unidecode>=1.3 in ./.tox/py36/lib/python3.6/site-packages (from python-slugify>=4.0.0->cookiecutter==2.0.0) (1.3) Requirement already satisfied: arrow in ./.tox/py36/lib/python3.6/site-packages (from jinja2-time>=0.2.0->cookiecutter==2.0.0) (1.2.3) Requirement already satisfied: typing-extensions>=3.6.4; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->click>=7.0->cookiecutter==2.0.0) (4.1.1) Requirement already satisfied: zipp>=0.5 in ./.tox/py36/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->click>=7.0->cookiecutter==2.0.0) (3.6.0) Requirement already satisfied: python-dateutil>=2.7.0 in ./.tox/py36/lib/python3.6/site-packages (from arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (2.8.2) Requirement already satisfied: six>=1.5 in ./.tox/py36/lib/python3.6/site-packages (from python-dateutil>=2.7.0->arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (1.16.0) Installing collected packages: cookiecutter Attempting uninstall: cookiecutter Found existing installation: cookiecutter 2.0.0 Uninstalling cookiecutter-2.0.0: Successfully uninstalled cookiecutter-2.0.0 Running setup.py develop for cookiecutter Successfully installed cookiecutter WARNING: You are using pip version 20.1.1; however, version 21.3.1 is available. You should consider upgrading via the '/home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python -m pip install --upgrade pip' command. py36 run-test: commands[1] | pytest --cov=cookiecutter tests/test_hooks.py::TestExternalHooks::test_run_hook ============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-7.0.1, pluggy-1.0.0 -- /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python cachedir: .tox/py36/.pytest_cache rootdir: /home/user/BugsInPy/temp/projects/cookiecutter, configfile: setup.cfg plugins: mock-3.6.1, cov-4.0.0 collecting ... collected 1 item tests/test_hooks.py::TestExternalHooks::test_run_hook FAILED [100%] =================================== FAILURES =================================== _______________________ TestExternalHooks.test_run_hook ________________________ self = <tests.test_hooks.TestExternalHooks object at 0x7f441efb6fd0> def test_run_hook(self): """Execute hook from specified template in specified output \ directory.""" tests_dir = os.path.join(self.repo_path, 'input{{hooks}}') with utils.work_in(self.repo_path): hooks.run_hook('pre_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt')) > assert os.path.isfile(os.path.join(tests_dir, 'shell_pre.txt')) E AssertionError: assert False E + where False = <function isfile at 0x7f4420d75c80>('/home/user/BugsInPy/temp/projects/cookiecutter/tests/test-hooks/input{{hooks}}/shell_pre.txt') E + where <function isfile at 0x7f4420d75c80> = <module 'posixpath' from '/opt/conda/envs/e1918bc774e14d4d9dca5a9720022972/lib/python3.6/posixpath.py'>.isfile E + where <module 'posixpath' from '/opt/conda/envs/e1918bc774e14d4d9dca5a9720022972/lib/python3.6/posixpath.py'> = os.path E + and '/home/user/BugsInPy/temp/projects/cookiecutter/tests/test-hooks/input{{hooks}}/shell_pre.txt' = <function join at 0x7f4420d1d620>('/home/user/BugsInPy/temp/projects/cookiecutter/tests/test-hooks/input{{hooks}}', 'shell_pre.txt') E + where <function join at 0x7f4420d1d620> = <module 'posixpath' from '/opt/conda/envs/e1918bc774e14d4d9dca5a9720022972/lib/python3.6/posixpath.py'>.join E + where <module 'posixpath' from '/opt/conda/envs/e1918bc774e14d4d9dca5a9720022972/lib/python3.6/posixpath.py'> = os.path tests/test_hooks.py:188: AssertionError ----------------------------- Captured stdout call ----------------------------- pre generation hook ----------- coverage: platform linux, python 3.6.9-final-0 ----------- Name Stmts Miss Cover Missing ----------------------------------------------------------- cookiecutter/__init__.py 1 0 100% cookiecutter/__main__.py 1 1 0% 2 cookiecutter/cli.py 51 51 0% 2-170 cookiecutter/config.py 53 53 0% 2-124 cookiecutter/environment.py 20 3 85% 35-36, 49 cookiecutter/exceptions.py 23 4 83% 120-122, 126 cookiecutter/extensions.py 26 6 77% 18, 31-35, 49 cookiecutter/find.py 17 17 0% 2-31 cookiecutter/generate.py 173 173 0% 2-372 cookiecutter/hooks.py 60 11 82% 54-55, 61, 74, 82-90, 124-125 cookiecutter/log.py 21 21 0% 2-51 cookiecutter/main.py 29 29 0% 7-109 cookiecutter/prompt.py 90 75 17% 19, 32, 41, 54-78, 86-96, 107-119, 139-156, 164-168, 177-226 cookiecutter/replay.py 27 27 0% 6-51 cookiecutter/repository.py 39 39 0% 2-127 cookiecutter/utils.py 48 23 52% 21-22, 38-45, 84-107 cookiecutter/vcs.py 53 53 0% 2-120 cookiecutter/zipfile.py 56 56 0% 2-112 ----------------------------------------------------------- TOTAL 788 642 19% =========================== short test summary info ============================ FAILED tests/test_hooks.py::TestExternalHooks::test_run_hook - AssertionError... ============================== 1 failed in 1.62s =============================== ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/pytest --cov=cookiecutter tests/test_hooks.py::TestExternalHooks::test_run_hook (exited with code 1) py37 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py37 ERROR: InterpreterNotFound: python3.7 py38 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py38 ERROR: InterpreterNotFound: python3.8 pypy3 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/pypy3 ERROR: InterpreterNotFound: pypy3 ___________________________________ summary ____________________________________ ERROR: lint: commands failed ERROR: py36: commands failed ERROR: py37: InterpreterNotFound: python3.7 ERROR: py38: InterpreterNotFound: python3.8 ERROR: pypy3: InterpreterNotFound: pypy3
tox tests/test_hooks.py::TestFindHooks::test_find_hook tox tests/test_hooks.py::TestExternalHooks::test_run_hook
d7e7b28811e474e14d1bed747115e47dcdd15ba3
tests/test_hooks.py
cookiecutter__cookiecutter-3
cookiecutter/cookiecutter
diff --git a/cookiecutter/prompt.py b/cookiecutter/prompt.py index 45a065b..da4ada2 100644 --- a/cookiecutter/prompt.py +++ b/cookiecutter/prompt.py @@ -88,7 +88,7 @@ def read_user_choice(var_name, options): )) user_choice = click.prompt( - prompt, type=click.Choice(choices), default=default + prompt, type=click.Choice(choices), default=default, show_choices=False ) return choice_map[user_choice]
diff --git a/tests/test_read_user_choice.py b/tests/test_read_user_choice.py index 0f9e003..0e81c2d 100644 --- a/tests/test_read_user_choice.py +++ b/tests/test_read_user_choice.py @@ -29,7 +29,8 @@ def test_click_invocation(mocker, user_choice, expected_value): prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), - default='1' + default='1', + show_choices=False )
GLOB sdist-make: /home/user/BugsInPy/temp/projects/cookiecutter/setup.py lint recreate: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint lint installdeps: pre-commit>=1.17.0 lint installed: cfgv==3.3.1,distlib==0.3.6,filelock==3.4.1,identify==2.4.4,importlib-metadata==4.8.3,importlib-resources==5.2.3,nodeenv==1.6.0,platformdirs==2.4.0,pre-commit==2.17.0,PyYAML==6.0,toml==0.10.2,typing-extensions==4.1.1,virtualenv==20.17.1,zipp==3.6.0 lint run-test-pre: PYTHONHASHSEED='2188846974' lint run-test: commands[0] | python -m pre_commit run tests/test_read_user_choice.py::test_click_invocation [WARNING] Unstaged files detected. [INFO] Stashing unstaged files to /root/.cache/pre-commit/patch1689392891-4249. [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Initializing environment for https://gitlab.com/pycqa/flake8. [INFO] Restored changes from /root/.cache/pre-commit/patch1689392891-4249. An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'fetch', 'origin', '--tags') return code: 128 expected return code: 0 stdout: (none) stderr: fatal: could not read Username for 'https://gitlab.com': No such device or address Check the log at /root/.cache/pre-commit/pre-commit.log ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint/bin/python -m pre_commit run tests/test_read_user_choice.py::test_click_invocation (exited with code 3) py27 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py27 ERROR: InterpreterNotFound: python2.7 py35 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py35 ERROR: InterpreterNotFound: python3.5 py36 recreate: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36 py36 installdeps: -rtest_requirements.txt py36 inst: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.6.0.zip py36 installed: arrow==1.2.3,attrs==22.2.0,binaryornot==0.4.4,certifi==2023.5.7,chardet==5.0.0,charset-normalizer==2.0.12,click==8.0.4,cookiecutter @ file:///home/user/BugsInPy/temp/projects/cookiecutter/.tox/.tmp/package/1/cookiecutter-1.6.0.zip,coverage==6.2,freezegun==1.2.2,future==0.18.3,idna==3.4,importlib-metadata==4.8.3,iniconfig==1.1.1,Jinja2==3.0.3,jinja2-time==0.2.0,MarkupSafe==2.0.1,packaging==21.3,pluggy==1.0.0,poyo==0.5.0,py==1.11.0,pyparsing==3.1.0,pytest==7.0.1,pytest-catchlog==1.2.2,pytest-cov==4.0.0,pytest-mock==3.6.1,python-dateutil==2.8.2,requests==2.27.1,six==1.16.0,tomli==1.2.3,typing-extensions==4.1.1,urllib3==1.26.16,whichcraft==0.6.1,zipp==3.6.0 py36 run-test-pre: PYTHONHASHSEED='2188846974' py36 run-test: commands[0] | pytest --cov=cookiecutter tests/test_read_user_choice.py::test_click_invocation ============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-7.0.1, pluggy-1.0.0 cachedir: .tox/py36/.pytest_cache rootdir: /home/user/BugsInPy/temp/projects/cookiecutter, configfile: setup.cfg plugins: mock-3.6.1, cov-4.0.0, catchlog-1.2.2 collected 4 items tests/test_read_user_choice.py FFFF [100%] =================================== FAILURES =================================== ________________________ test_click_invocation[1-hello] ________________________ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986666823072'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986666823072'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986667209840'>} introspection = "\nKwargs:\nassert {'default': '...86667209840'>} == {'default': '...86667209840'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986666823072'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} expected = (('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',), {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>}) _error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7f512f912950> actual = call('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986667209840'>) cause = None def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None > raise AssertionError(_error_message()) from cause E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986667209840'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986667209840'>) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:814: AssertionError During handling of the above exception, another exception occurred: __wrapped_mock_method__ = <function NonCallableMock.assert_called_once_with at 0x7f512efae840> args = (<MagicMock name='prompt' id='139986666823072'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986666823072'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} self = <MagicMock name='prompt' id='139986666823072'> def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) > return self.assert_called_with(*args, **kwargs) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:825: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ args = (<MagicMock name='prompt' id='139986666823072'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} __tracebackhide__ = True def wrap_assert_called_with(*args: Any, **kwargs: Any) -> None: __tracebackhide__ = True > assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:447: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986666823072'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986667209840'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986666823072'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986667209840'>} introspection = "\nKwargs:\nassert {'default': '...86667209840'>} == {'default': '...86667209840'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return except AssertionError as e: if getattr(e, "_mock_introspection_applied", 0): msg = str(e) else: __mock_self = args[0] msg = str(e) if __mock_self.call_args is not None: actual_args, actual_kwargs = __mock_self.call_args introspection = "" try: assert actual_args == args[1:] except AssertionError as e_args: introspection += "\nArgs:\n" + str(e_args) try: assert actual_kwargs == kwargs except AssertionError as e_kwargs: introspection += "\nKwargs:\n" + str(e_kwargs) if introspection: msg += "\n\npytest introspection follows:\n" + introspection e = AssertionError(msg) e._mock_introspection_applied = True # type:ignore[attr-defined] > raise e E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986667209840'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986667209840'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86667209840'>} == {'default': '...86667209840'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:437: AssertionError During handling of the above exception, another exception occurred: mocker = <pytest_mock.plugin.MockerFixture object at 0x7f512f929ba8> user_choice = 1, expected_value = 'hello' @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', > show_choices=False ) E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986667209840'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986667209840'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86667209840'>} == {'default': '...86667209840'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff tests/test_read_user_choice.py:33: AssertionError ________________________ test_click_invocation[2-world] ________________________ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986643301992'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986643301992'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986644657376'>} introspection = "\nKwargs:\nassert {'default': '...86644657376'>} == {'default': '...86644657376'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986643301992'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} expected = (('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',), {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>}) _error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7f512e4707b8> actual = call('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644657376'>) cause = None def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None > raise AssertionError(_error_message()) from cause E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644657376'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644657376'>) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:814: AssertionError During handling of the above exception, another exception occurred: __wrapped_mock_method__ = <function NonCallableMock.assert_called_once_with at 0x7f512efae840> args = (<MagicMock name='prompt' id='139986643301992'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986643301992'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} self = <MagicMock name='prompt' id='139986643301992'> def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) > return self.assert_called_with(*args, **kwargs) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:825: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ args = (<MagicMock name='prompt' id='139986643301992'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} __tracebackhide__ = True def wrap_assert_called_with(*args: Any, **kwargs: Any) -> None: __tracebackhide__ = True > assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:447: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986643301992'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644657376'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986643301992'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986644657376'>} introspection = "\nKwargs:\nassert {'default': '...86644657376'>} == {'default': '...86644657376'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return except AssertionError as e: if getattr(e, "_mock_introspection_applied", 0): msg = str(e) else: __mock_self = args[0] msg = str(e) if __mock_self.call_args is not None: actual_args, actual_kwargs = __mock_self.call_args introspection = "" try: assert actual_args == args[1:] except AssertionError as e_args: introspection += "\nArgs:\n" + str(e_args) try: assert actual_kwargs == kwargs except AssertionError as e_kwargs: introspection += "\nKwargs:\n" + str(e_kwargs) if introspection: msg += "\n\npytest introspection follows:\n" + introspection e = AssertionError(msg) e._mock_introspection_applied = True # type:ignore[attr-defined] > raise e E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644657376'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644657376'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86644657376'>} == {'default': '...86644657376'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:437: AssertionError During handling of the above exception, another exception occurred: mocker = <pytest_mock.plugin.MockerFixture object at 0x7f512f905048> user_choice = 2, expected_value = 'world' @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', > show_choices=False ) E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644657376'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644657376'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86644657376'>} == {'default': '...86644657376'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff tests/test_read_user_choice.py:33: AssertionError _________________________ test_click_invocation[3-foo] _________________________ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986643729432'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986643729432'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986643525192'>} introspection = "\nKwargs:\nassert {'default': '...86643525192'>} == {'default': '...86643525192'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986643729432'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} expected = (('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',), {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>}) _error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7f512e470e18> actual = call('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986643525192'>) cause = None def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None > raise AssertionError(_error_message()) from cause E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986643525192'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986643525192'>) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:814: AssertionError During handling of the above exception, another exception occurred: __wrapped_mock_method__ = <function NonCallableMock.assert_called_once_with at 0x7f512efae840> args = (<MagicMock name='prompt' id='139986643729432'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986643729432'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} self = <MagicMock name='prompt' id='139986643729432'> def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) > return self.assert_called_with(*args, **kwargs) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:825: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ args = (<MagicMock name='prompt' id='139986643729432'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} __tracebackhide__ = True def wrap_assert_called_with(*args: Any, **kwargs: Any) -> None: __tracebackhide__ = True > assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:447: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986643729432'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986643525192'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986643729432'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986643525192'>} introspection = "\nKwargs:\nassert {'default': '...86643525192'>} == {'default': '...86643525192'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return except AssertionError as e: if getattr(e, "_mock_introspection_applied", 0): msg = str(e) else: __mock_self = args[0] msg = str(e) if __mock_self.call_args is not None: actual_args, actual_kwargs = __mock_self.call_args introspection = "" try: assert actual_args == args[1:] except AssertionError as e_args: introspection += "\nArgs:\n" + str(e_args) try: assert actual_kwargs == kwargs except AssertionError as e_kwargs: introspection += "\nKwargs:\n" + str(e_kwargs) if introspection: msg += "\n\npytest introspection follows:\n" + introspection e = AssertionError(msg) e._mock_introspection_applied = True # type:ignore[attr-defined] > raise e E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986643525192'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986643525192'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86643525192'>} == {'default': '...86643525192'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:437: AssertionError During handling of the above exception, another exception occurred: mocker = <pytest_mock.plugin.MockerFixture object at 0x7f512e3b51d0> user_choice = 3, expected_value = 'foo' @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', > show_choices=False ) E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986643525192'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986643525192'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86643525192'>} == {'default': '...86643525192'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff tests/test_read_user_choice.py:33: AssertionError _________________________ test_click_invocation[4-bar] _________________________ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986644401736'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986644401736'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986644773520'>} introspection = "\nKwargs:\nassert {'default': '...86644773520'>} == {'default': '...86644773520'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986644401736'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} expected = (('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',), {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>}) _error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7f512e3b7510> actual = call('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644773520'>) cause = None def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None > raise AssertionError(_error_message()) from cause E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644773520'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644773520'>) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:814: AssertionError During handling of the above exception, another exception occurred: __wrapped_mock_method__ = <function NonCallableMock.assert_called_once_with at 0x7f512efae840> args = (<MagicMock name='prompt' id='139986644401736'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: > __wrapped_mock_method__(*args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:414: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _mock_self = <MagicMock name='prompt' id='139986644401736'> args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} self = <MagicMock name='prompt' id='139986644401736'> def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) > return self.assert_called_with(*args, **kwargs) /opt/conda/envs/76d4d4db462c2965aaa44339b7ec9c46/lib/python3.6/unittest/mock.py:825: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ args = (<MagicMock name='prompt' id='139986644401736'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} __tracebackhide__ = True def wrap_assert_called_with(*args: Any, **kwargs: Any) -> None: __tracebackhide__ = True > assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs) .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:447: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __wrapped_mock_method__ = <function NonCallableMock.assert_called_with at 0x7f512efae7b8> args = (<MagicMock name='prompt' id='139986644401736'>, 'Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4') kwargs = {'default': '1', 'show_choices': False, 'type': <MagicMock name='Choice()' id='139986644773520'>} __tracebackhide__ = True msg = "Expected call: prompt('Select varname:\\n1 - hello\\n2 - world\\n3 - foo\\n4 - bar\\nChoose from 1, 2, 3, 4', default...ntical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" __mock_self = <MagicMock name='prompt' id='139986644401736'> actual_args = ('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4',) actual_kwargs = {'default': '1', 'type': <MagicMock name='Choice()' id='139986644773520'>} introspection = "\nKwargs:\nassert {'default': '...86644773520'>} == {'default': '...86644773520'>}\n Omitting 2 identical items, use -vv to show\n Right contains 1 more item:\n {'show_choices': False}\n Use -v to get the full diff" @py_assert2 = None, @py_assert1 = False def assert_wrapper( __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return except AssertionError as e: if getattr(e, "_mock_introspection_applied", 0): msg = str(e) else: __mock_self = args[0] msg = str(e) if __mock_self.call_args is not None: actual_args, actual_kwargs = __mock_self.call_args introspection = "" try: assert actual_args == args[1:] except AssertionError as e_args: introspection += "\nArgs:\n" + str(e_args) try: assert actual_kwargs == kwargs except AssertionError as e_kwargs: introspection += "\nKwargs:\n" + str(e_kwargs) if introspection: msg += "\n\npytest introspection follows:\n" + introspection e = AssertionError(msg) e._mock_introspection_applied = True # type:ignore[attr-defined] > raise e E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644773520'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644773520'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86644773520'>} == {'default': '...86644773520'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff .tox/py36/lib/python3.6/site-packages/pytest_mock/plugin.py:437: AssertionError During handling of the above exception, another exception occurred: mocker = <pytest_mock.plugin.MockerFixture object at 0x7f512e39b3c8> user_choice = 4, expected_value = 'bar' @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', > show_choices=False ) E AssertionError: Expected call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', show_choices=False, type=<MagicMock name='Choice()' id='139986644773520'>) E Actual call: prompt('Select varname:\n1 - hello\n2 - world\n3 - foo\n4 - bar\nChoose from 1, 2, 3, 4', default='1', type=<MagicMock name='Choice()' id='139986644773520'>) E E pytest introspection follows: E E Kwargs: E assert {'default': '...86644773520'>} == {'default': '...86644773520'>} E Omitting 2 identical items, use -vv to show E Right contains 1 more item: E {'show_choices': False} E Use -v to get the full diff tests/test_read_user_choice.py:33: AssertionError ----------- coverage: platform linux, python 3.6.9-final-0 ----------- Name Stmts Miss Cover ------------------------------------------------- cookiecutter/__init__.py 2 0 100% cookiecutter/__main__.py 3 3 0% cookiecutter/cli.py 50 50 0% cookiecutter/config.py 52 52 0% cookiecutter/environment.py 21 13 38% cookiecutter/exceptions.py 24 4 83% cookiecutter/extensions.py 9 9 0% cookiecutter/find.py 18 18 0% cookiecutter/generate.py 166 166 0% cookiecutter/hooks.py 61 61 0% cookiecutter/log.py 22 22 0% cookiecutter/main.py 31 31 0% cookiecutter/prompt.py 90 63 30% cookiecutter/replay.py 30 30 0% cookiecutter/repository.py 39 39 0% cookiecutter/utils.py 50 32 36% cookiecutter/vcs.py 54 54 0% cookiecutter/zipfile.py 61 61 0% ------------------------------------------------- TOTAL 783 708 10% =========================== short test summary info ============================ FAILED tests/test_read_user_choice.py::test_click_invocation[1-hello] - Asser... FAILED tests/test_read_user_choice.py::test_click_invocation[2-world] - Asser... FAILED tests/test_read_user_choice.py::test_click_invocation[3-foo] - Asserti... FAILED tests/test_read_user_choice.py::test_click_invocation[4-bar] - Asserti... ============================== 4 failed in 2.62s =============================== /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/lib/python3.6/site-packages/_pytest/config/__init__.py:455: PytestConfigWarning: pytest-catchlog plugin has been merged into the core, please remove it from your requirements. name.replace("_", "-") ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/pytest --cov=cookiecutter tests/test_read_user_choice.py::test_click_invocation (exited with code 1) py37 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py37 ERROR: InterpreterNotFound: python3.7 pypy create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/pypy ERROR: InterpreterNotFound: pypy ___________________________________ summary ____________________________________ ERROR: lint: commands failed ERROR: py27: InterpreterNotFound: python2.7 ERROR: py35: InterpreterNotFound: python3.5 ERROR: py36: commands failed ERROR: py37: InterpreterNotFound: python3.7 ERROR: pypy: InterpreterNotFound: pypy
tox tests/test_read_user_choice.py::test_click_invocation
5c282f020a8db7e5e7c4e7b51b010556ca31fb7f
tests/test_read_user_choice.py
cookiecutter__cookiecutter-1
cookiecutter/cookiecutter
diff --git a/cookiecutter/generate.py b/cookiecutter/generate.py index 37365a4..c526b97 100644 --- a/cookiecutter/generate.py +++ b/cookiecutter/generate.py @@ -82,7 +82,7 @@ def generate_context( context = OrderedDict([]) try: - with open(context_file) as file_handle: + with open(context_file, encoding='utf-8') as file_handle: obj = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more
diff --git a/tests/test_generate_context.py b/tests/test_generate_context.py index 26e7d4d..69d0148 100644 --- a/tests/test_generate_context.py +++ b/tests/test_generate_context.py @@ -108,6 +108,17 @@ def test_default_context_replacement_in_generate_context(): assert generated_context == expected_context +def test_generate_context_decodes_non_ascii_chars(): + """Verify `generate_context` correctly decodes non-ascii chars.""" + expected_context = {'non_ascii': OrderedDict([('full_name', 'éèà'),])} + + generated_context = generate.generate_context( + context_file='tests/test-generate-context/non_ascii.json' + ) + + assert generated_context == expected_context + + @pytest.fixture def template_context(): """Fixture. Populates template content for future tests."""
lint create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint lint installdeps: pre-commit>=1.20.0 lint installed: cfgv==3.3.1,distlib==0.3.6,filelock==3.4.1,identify==2.4.4,importlib-metadata==4.8.3,importlib-resources==5.2.3,nodeenv==1.6.0,platformdirs==2.4.0,pre-commit==2.17.0,PyYAML==6.0,toml==0.10.2,typing-extensions==4.1.1,virtualenv==20.17.1,zipp==3.6.0 lint run-test-pre: PYTHONHASHSEED='2240371620' lint run-test: commands[0] | python -m pre_commit run tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars [WARNING] Unstaged files detected. [INFO] Stashing unstaged files to /root/.cache/pre-commit/patch1689391652-972. [INFO] Initializing environment for https://github.com/python/black.git. [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Initializing environment for https://gitlab.com/pycqa/flake8. [INFO] Restored changes from /root/.cache/pre-commit/patch1689391652-972. An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'fetch', 'origin', '--tags') return code: 128 expected return code: 0 stdout: (none) stderr: fatal: could not read Username for 'https://gitlab.com': No such device or address Check the log at /root/.cache/pre-commit/pre-commit.log ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/lint/bin/python -m pre_commit run tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars (exited with code 3) py36 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36 py36 installdeps: -rtest_requirements.txt py36 installed: attrs==22.2.0,coverage==6.2,freezegun==1.2.2,importlib-metadata==4.8.3,iniconfig==1.1.1,packaging==21.3,pluggy==1.0.0,py==1.11.0,pyparsing==3.1.0,pytest==7.0.1,pytest-cov==4.0.0,pytest-mock==3.6.1,python-dateutil==2.8.2,six==1.16.0,tomli==1.2.3,typing-extensions==4.1.1,zipp==3.6.0 py36 run-test-pre: PYTHONHASHSEED='2240371620' py36 run-test: commands[0] | pip install -e . Obtaining file:///home/user/BugsInPy/temp/projects/cookiecutter Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' Collecting python-slugify>=4.0.0 Using cached python_slugify-6.1.2-py2.py3-none-any.whl (9.4 kB) Collecting poyo>=0.5.0 Using cached poyo-0.5.0-py2.py3-none-any.whl (10 kB) Collecting jinja2-time>=0.2.0 Using cached jinja2_time-0.2.0-py2.py3-none-any.whl (6.4 kB) Collecting MarkupSafe<2.0.0 Using cached MarkupSafe-1.1.1-cp36-cp36m-manylinux2010_x86_64.whl (32 kB) Collecting binaryornot>=0.4.4 Using cached binaryornot-0.4.4-py2.py3-none-any.whl (9.0 kB) Collecting click>=7.0 Downloading click-8.0.4-py3-none-any.whl (97 kB) Collecting Jinja2<3.0.0 Using cached Jinja2-2.11.3-py2.py3-none-any.whl (125 kB) Collecting requests>=2.23.0 Using cached requests-2.27.1-py2.py3-none-any.whl (63 kB) Collecting text-unidecode>=1.3 Using cached text_unidecode-1.3-py2.py3-none-any.whl (78 kB) Collecting arrow Downloading arrow-1.2.3-py3-none-any.whl (66 kB) Collecting chardet>=3.0.2 Using cached chardet-5.0.0-py3-none-any.whl (193 kB) Requirement already satisfied: importlib-metadata; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from click>=7.0->cookiecutter==2.0.0) (4.8.3) Collecting urllib3<1.27,>=1.21.1 Using cached urllib3-1.26.16-py2.py3-none-any.whl (143 kB) Collecting charset-normalizer~=2.0.0; python_version >= "3" Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB) Collecting idna<4,>=2.5; python_version >= "3" Using cached idna-3.4-py3-none-any.whl (61 kB) Collecting certifi>=2017.4.17 Downloading certifi-2023.5.7-py3-none-any.whl (156 kB) Requirement already satisfied: python-dateutil>=2.7.0 in ./.tox/py36/lib/python3.6/site-packages (from arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (2.8.2) Requirement already satisfied: typing-extensions; python_version < "3.8" in ./.tox/py36/lib/python3.6/site-packages (from arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (4.1.1) Requirement already satisfied: zipp>=0.5 in ./.tox/py36/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->click>=7.0->cookiecutter==2.0.0) (3.6.0) Requirement already satisfied: six>=1.5 in ./.tox/py36/lib/python3.6/site-packages (from python-dateutil>=2.7.0->arrow->jinja2-time>=0.2.0->cookiecutter==2.0.0) (1.16.0) Installing collected packages: text-unidecode, python-slugify, poyo, arrow, MarkupSafe, Jinja2, jinja2-time, chardet, binaryornot, click, urllib3, charset-normalizer, idna, certifi, requests, cookiecutter Running setup.py develop for cookiecutter Successfully installed Jinja2-2.11.3 MarkupSafe-1.1.1 arrow-1.2.3 binaryornot-0.4.4 certifi-2023.5.7 chardet-5.0.0 charset-normalizer-2.0.12 click-8.0.4 cookiecutter idna-3.4 jinja2-time-0.2.0 poyo-0.5.0 python-slugify-6.1.2 requests-2.27.1 text-unidecode-1.3 urllib3-1.26.16 WARNING: You are using pip version 20.1.1; however, version 21.3.1 is available. You should consider upgrading via the '/home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python -m pip install --upgrade pip' command. py36 run-test: commands[1] | pytest --cov=cookiecutter tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars ============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-7.0.1, pluggy-1.0.0 -- /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/python cachedir: .tox/py36/.pytest_cache rootdir: /home/user/BugsInPy/temp/projects/cookiecutter, configfile: setup.cfg plugins: mock-3.6.1, cov-4.0.0 collecting ... collected 1 item tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars FAILED [100%] =================================== FAILURES =================================== ________________ test_generate_context_decodes_non_ascii_chars _________________ def test_generate_context_decodes_non_ascii_chars(): """Verify `generate_context` correctly decodes non-ascii chars.""" expected_context = {'non_ascii': OrderedDict([('full_name', 'éèà'),])} generated_context = generate.generate_context( > context_file='tests/test-generate-context/non_ascii.json' ) tests/test_generate_context.py:116: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ context_file = 'tests/test-generate-context/non_ascii.json' default_context = None, extra_context = None def generate_context( context_file='cookiecutter.json', default_context=None, extra_context=None ): """Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value pairs for populating the cookiecutter's variables. :param default_context: Dictionary containing config to take into account. :param extra_context: Dictionary containing configuration overrides """ context = OrderedDict([]) try: > with open(context_file) as file_handle: E FileNotFoundError: [Errno 2] No such file or directory: 'tests/test-generate-context/non_ascii.json' cookiecutter/generate.py:85: FileNotFoundError ----------- coverage: platform linux, python 3.6.9-final-0 ----------- Name Stmts Miss Cover Missing ----------------------------------------------------------- cookiecutter/__init__.py 1 0 100% cookiecutter/__main__.py 1 1 0% 2 cookiecutter/cli.py 55 55 0% 2-185 cookiecutter/config.py 53 53 0% 2-124 cookiecutter/environment.py 20 13 35% 23-36, 44-49, 64 cookiecutter/exceptions.py 23 4 83% 120-122, 126 cookiecutter/extensions.py 26 26 0% 2-51 cookiecutter/find.py 17 12 29% 16-31 cookiecutter/generate.py 175 148 15% 38-45, 50-67, 86, 90-111, 135-189, 196-218, 223-226, 241-252, 272-380 cookiecutter/hooks.py 64 47 27% 29-36, 51-64, 73-93, 103-114, 125-131 cookiecutter/log.py 21 21 0% 2-51 cookiecutter/main.py 30 30 0% 7-115 cookiecutter/prompt.py 90 75 17% 19, 32, 41, 54-78, 86-96, 107-119, 139-156, 164-168, 177-226 cookiecutter/replay.py 27 27 0% 6-51 cookiecutter/repository.py 39 39 0% 2-127 cookiecutter/utils.py 48 32 33% 21-22, 30, 38-45, 54-60, 68-69, 84-107 cookiecutter/vcs.py 53 53 0% 2-120 cookiecutter/zipfile.py 56 56 0% 2-112 ----------------------------------------------------------- TOTAL 799 692 13% =========================== short test summary info ============================ FAILED tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars ============================== 1 failed in 1.05s =============================== ERROR: InvocationError for command /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py36/bin/pytest --cov=cookiecutter tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars (exited with code 1) py37 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py37 ERROR: InterpreterNotFound: python3.7 py38 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/py38 ERROR: InterpreterNotFound: python3.8 pypy3 create: /home/user/BugsInPy/temp/projects/cookiecutter/.tox/pypy3 ERROR: InterpreterNotFound: pypy3 ___________________________________ summary ____________________________________ ERROR: lint: commands failed ERROR: py36: commands failed ERROR: py37: InterpreterNotFound: python3.7 ERROR: py38: InterpreterNotFound: python3.8 ERROR: pypy3: InterpreterNotFound: pypy3
tox tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars
c15633745df6abdb24e02746b82aadb20b8cdf8c
tests/test_generate_context.py
tiangolo__fastapi-4
tiangolo/fastapi
diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index d53ee6b..91f90ec 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -180,7 +180,9 @@ def get_openapi_path( operation_parameters = get_openapi_operation_parameters(all_route_params) parameters.extend(operation_parameters) if parameters: - operation["parameters"] = parameters + operation["parameters"] = list( + {param["name"]: param for param in parameters}.values() + ) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( body_field=route.body_field, model_name_map=model_name_map
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_param_in_path_and_dependency.py F [100%] =================================== FAILURES =================================== ______________________________ test_reused_param _______________________________ def test_reused_param(): response = client.get("/openapi.json") data = response.json() > assert data == openapi_schema E AssertionError: assert {'components'...ead Users'}}}} == {'components'...ead Users'}}}} E Omitting 3 identical items, use -vv to show E Differing items: E {'paths': {'/users/{user_id}': {'get': {'operationId': 'read_users_users__user_id__get', 'parameters': [{'in': 'path',...on': 'Successful Response'}, '422': {'content': {...}, 'description': 'Validation Error'}}, 'summary': 'Read Users'}}}} != {'paths': {'/users/{user_id}': {'get': {'operationId': 'read_users_users__user_id__get', 'parameters': [{'in': 'path',...on': 'Successful Response'}, '422': {'content': {...}, 'description': 'Validation Error'}}, 'summary': 'Read Users'}}}} E Use -v to get the full diff tests/test_param_in_path_and_dependency.py:88: AssertionError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_param_in_path_and_dependency.py::test_reused_param - Assert... ======================== 1 failed, 6 warnings in 2.24s =========================
pytest tests/test_param_in_path_and_dependency.py::test_reused_param
7ccd81f70653857bd8f3a15ee946aa3fb0edc2cb
tests/test_param_in_path_and_dependency.py
tiangolo__fastapi-13
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index e768c3a..2bdf46d 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -285,11 +285,11 @@ class APIRouter(routing.Router): assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" + if responses is None: + responses = {} for route in router.routes: if isinstance(route, APIRoute): - if responses is None: - responses = {} - responses = {**responses, **route.responses} + combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, @@ -299,7 +299,7 @@ class APIRouter(routing.Router): summary=route.summary, description=route.description, response_description=route.response_description, - responses=responses, + responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id,
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_additional_responses_router.py F [100%] =================================== FAILURES =================================== _____________________________ test_openapi_schema ______________________________ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 > assert response.json() == openapi_schema E AssertionError: assert {'info': {'ti...': 'C Get'}}}} == {'info': {'ti...': 'C Get'}}}} E Omitting 2 identical items, use -vv to show E Differing items: E {'paths': {'/a': {'get': {'operationId': 'a_a_get', 'responses': {'200': {'content': {...}, 'description': 'Successful...: 'Successful Response'}, '501': {'description': 'Error 3'}, '502': {'description': 'Error 2'}}, 'summary': 'C Get'}}}} != {'paths': {'/a': {'get': {'operationId': 'a_a_get', 'responses': {'200': {'content': {...}, 'description': 'Successful...': {'content': {...}, 'description': 'Successful Response'}, '501': {'description': 'Error 3'}}, 'summary': 'C Get'}}}} E Use -v to get the full diff tests/test_additional_responses_router.py:77: AssertionError =============================== warnings summary =============================== /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.26') /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_additional_responses_router.py::test_openapi_schema - Asser... ======================== 1 failed, 7 warnings in 0.81s =========================
pytest tests/test_additional_responses_router.py::test_openapi_schema
6f7f9268f6b03f42831dcfeaa5c15ba9813333ec
tests/test_additional_responses_router.py
tiangolo__fastapi-9
tiangolo/fastapi
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f9e42d0..7f0f590 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -559,6 +559,8 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) + + BodySchema_kwargs: Dict[str, Any] = dict(default=None) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): @@ -566,6 +568,14 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: else: BodySchema = params.Body + body_param_media_types = [ + getattr(f.schema, "media_type") + for f in flat_dependant.body_params + if isinstance(f.schema, params.Body) + ] + if len(set(body_param_media_types)) == 1: + BodySchema_kwargs["media_type"] = body_param_media_types[0] + field = Field( name="body", type_=BodyModel, @@ -574,6 +584,6 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: model_config=BaseConfig, class_validators={}, alias="body", - schema=BodySchema(None), + schema=BodySchema(**BodySchema_kwargs), ) return field
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_request_body_parameters_media_type.py F [100%] =================================== FAILURES =================================== _____________________________ test_openapi_schema ______________________________ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 openapi_schema = response.json() > assert ( openapi_schema["paths"]["/products"]["post"]["requestBody"] == create_product_request_body ) E AssertionError: assert {'content': {...quired': True} == {'content': {...quired': True} E Omitting 1 identical items, use -vv to show E Differing items: E {'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Body_create_product_products_post'}}}} != {'content': {'application/vnd.api+json': {'schema': {'$ref': '#/components/schemas/Body_create_product_products_post'}}}} E Use -v to get the full diff tests/test_request_body_parameters_media_type.py:60: AssertionError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_request_body_parameters_media_type.py::test_openapi_schema ======================== 1 failed, 7 warnings in 0.77s =========================
pytest tests/test_request_body_parameters_media_type.py::test_openapi_schema
a7a92bc63768ccee3f3afc2b73b2c581928dfe75
tests/test_request_body_parameters_media_type.py
tiangolo__fastapi-7
tiangolo/fastapi
diff --git a/fastapi/exception_handlers.py b/fastapi/exception_handlers.py index cda2f8c..2b286d7 100644 --- a/fastapi/exception_handlers.py +++ b/fastapi/exception_handlers.py @@ -1,3 +1,4 @@ +from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request @@ -19,5 +20,6 @@ async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( - status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()} + status_code=HTTP_422_UNPROCESSABLE_ENTITY, + content={"detail": jsonable_encoder(exc.errors())}, )
diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py index ef07c2a8..5824cda2 100644 --- a/tests/test_multi_body_errors.py +++ b/tests/test_multi_body_errors.py @@ -1,7 +1,8 @@ +from decimal import Decimal from typing import List from fastapi import FastAPI -from pydantic import BaseModel +from pydantic import BaseModel, condecimal from starlette.testclient import TestClient app = FastAPI() @@ -9,7 +10,7 @@ app = FastAPI() class Item(BaseModel): name: str - age: int + age: condecimal(gt=Decimal(0.0)) @app.post("/items/") @@ -67,7 +68,7 @@ openapi_schema = { "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "age": {"title": "Age", "type": "integer"}, + "age": {"title": "Age", "exclusiveMinimum": 0.0, "type": "number"}, }, }, "ValidationError": { @@ -99,6 +100,17 @@ openapi_schema = { }, } +single_error = { + "detail": [ + { + "ctx": {"limit_value": 0.0}, + "loc": ["body", "item", 0, "age"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] +} + multiple_errors = { "detail": [ { @@ -108,8 +120,8 @@ multiple_errors = { }, { "loc": ["body", "item", 0, "age"], - "msg": "value is not a valid integer", - "type": "type_error.integer", + "msg": "value is not a valid decimal", + "type": "type_error.decimal", }, { "loc": ["body", "item", 1, "name"], @@ -118,8 +130,8 @@ multiple_errors = { }, { "loc": ["body", "item", 1, "age"], - "msg": "value is not a valid integer", - "type": "type_error.integer", + "msg": "value is not a valid decimal", + "type": "type_error.decimal", }, ] } @@ -137,7 +149,13 @@ def test_put_correct_body(): assert response.json() == {"item": [{"name": "Foo", "age": 5}]} -def test_put_incorrect_body(): +def test_jsonable_encoder_requiring_error(): + response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}]) + assert response.status_code == 422 + assert response.json() == single_error + + +def test_put_incorrect_body_multiple(): response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}]) assert response.status_code == 422 assert response.json() == multiple_errors
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_multi_body_errors.py F [100%] =================================== FAILURES =================================== ____________________ test_jsonable_encoder_requiring_error _____________________ def test_jsonable_encoder_requiring_error(): > response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}]) tests/test_multi_body_errors.py:153: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/requests/sessions.py:578: in post return self.request('POST', url, data=data, json=json, **kwargs) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:140: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/applications.py:134: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/middleware/errors.py:178: in __call__ raise exc from None /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/middleware/errors.py:156: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/exceptions.py:81: in __call__ response = await handler(request, exc) fastapi/exception_handlers.py:21: in request_validation_exception_handler return JSONResponse( /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/responses.py:42: in __init__ self.body = self.render(content) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/starlette/responses.py:146: in render return json.dumps( /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/json/__init__.py:234: in dumps return cls( /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/json/encoder.py:199: in encode chunks = self.iterencode(o, _one_shot=True) /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/json/encoder.py:257: in iterencode return _iterencode(o, 0) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <json.encoder.JSONEncoder object at 0x7fd69819b250>, o = Decimal('0') def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) """ > raise TypeError(f'Object of type {o.__class__.__name__} ' f'is not JSON serializable') E TypeError: Object of type Decimal is not JSON serializable /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/json/encoder.py:179: TypeError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_multi_body_errors.py::test_jsonable_encoder_requiring_error ======================== 1 failed, 6 warnings in 1.18s =========================
pytest tests/test_multi_body_errors.py::test_jsonable_encoder_requiring_error
cc4c13e4ae3f65fc76c23962b316df4a60e0c7e0
tests/test_multi_body_errors.py
tiangolo__fastapi-12
tiangolo/fastapi
diff --git a/fastapi/security/http.py b/fastapi/security/http.py index f41d8d9..362390b 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -112,10 +112,13 @@ class HTTPBearer(HTTPBase): else: return None if scheme.lower() != "bearer": - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail="Invalid authentication credentials", - ) + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
diff --git a/tests/test_security_http_bearer_optional.py b/tests/test_security_http_bearer_optional.py index 5a690c52..d34433ec 100644 --- a/tests/test_security_http_bearer_optional.py +++ b/tests/test_security_http_bearer_optional.py @@ -64,5 +64,5 @@ def test_security_http_bearer_no_credentials(): def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) - assert response.status_code == 403 - assert response.json() == {"detail": "Invalid authentication credentials"} + assert response.status_code == 200 + assert response.json() == {"msg": "Create an account first"}
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_security_http_bearer_optional.py F [100%] =================================== FAILURES =================================== ____________ test_security_http_bearer_incorrect_scheme_credentials ____________ def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) > assert response.status_code == 200 E assert 403 == 200 E + where 403 = <Response [403]>.status_code tests/test_security_http_bearer_optional.py:67: AssertionError =============================== warnings summary =============================== /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.26') /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_security_http_bearer_optional.py::test_security_http_bearer_incorrect_scheme_credentials ======================== 1 failed, 7 warnings in 0.97s =========================
pytest tests/test_security_http_bearer_optional.py::test_security_http_bearer_incorrect_scheme_credentials
d61f5e4b555b123bf222503fc0e076cbae6a7ebc
tests/test_security_http_bearer_optional.py
tiangolo__fastapi-6
tiangolo/fastapi
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 956ffff..a1cc0b9 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -629,9 +629,9 @@ async def request_body_to_args( for field in required_params: value: Any = None if received_body is not None: - if field.shape in sequence_shapes and isinstance( - received_body, FormData - ): + if ( + field.shape in sequence_shapes or field.type_ in sequence_types + ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias)
RUN EVERY COMMAND 0 ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_forms_from_non_typing_sequences.py F [100%] =================================== FAILURES =================================== ________________________ test_python_list_param_as_form ________________________ def test_python_list_param_as_form(): response = client.post( "/form/python-list", data={"items": ["first", "second", "third"]} ) > assert response.status_code == 200 E assert 422 == 200 E + where 422 = <Response [422]>.status_code tests/test_forms_from_non_typing_sequences.py:29: AssertionError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_forms_from_non_typing_sequences.py::test_python_list_param_as_form ======================== 1 failed, 6 warnings in 0.66s ========================= RUN EVERY COMMAND 1 pytest tests/test_forms_from_non_typing_sequences.py::test_python_list_param_as_form ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_forms_from_non_typing_sequences.py F [100%] =================================== FAILURES =================================== ________________________ test_python_set_param_as_form _________________________ def test_python_set_param_as_form(): response = client.post( "/form/python-set", data={"items": ["first", "second", "third"]} ) > assert response.status_code == 200 E assert 422 == 200 E + where 422 = <Response [422]>.status_code tests/test_forms_from_non_typing_sequences.py:37: AssertionError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_forms_from_non_typing_sequences.py::test_python_set_param_as_form ======================== 1 failed, 6 warnings in 0.44s ========================= RUN EVERY COMMAND 2 pytest tests/test_forms_from_non_typing_sequences.py::test_python_set_param_as_form ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_forms_from_non_typing_sequences.py F [100%] =================================== FAILURES =================================== _______________________ test_python_tuple_param_as_form ________________________ def test_python_tuple_param_as_form(): response = client.post( "/form/python-tuple", data={"items": ["first", "second", "third"]} ) > assert response.status_code == 200 E assert 422 == 200 E + where 422 = <Response [422]>.status_code tests/test_forms_from_non_typing_sequences.py:45: AssertionError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_forms_from_non_typing_sequences.py::test_python_tuple_param_as_form ======================== 1 failed, 6 warnings in 0.55s =========================
pytest tests/test_forms_from_non_typing_sequences.py::test_python_list_param_as_form pytest tests/test_forms_from_non_typing_sequences.py::test_python_set_param_as_form pytest tests/test_forms_from_non_typing_sequences.py::test_python_tuple_param_as_form
5db99a27cf640864b4793807811848698c5ff4a2
tests/test_forms_from_non_typing_sequences.py
tiangolo__fastapi-2
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index b90935e..1ec0b69 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -498,7 +498,12 @@ class APIRouter(routing.Router): def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: - route = APIWebSocketRoute(path, endpoint=endpoint, name=name) + route = APIWebSocketRoute( + path, + endpoint=endpoint, + name=name, + dependency_overrides_provider=self.dependency_overrides_provider, + ) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable:
diff --git a/tests/test_ws_router.py b/tests/test_ws_router.py index fd19e650..dd045612 100644 --- a/tests/test_ws_router.py +++ b/tests/test_ws_router.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, FastAPI, WebSocket +from fastapi import APIRouter, Depends, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter() @@ -34,6 +34,19 @@ async def routerindex(websocket: WebSocket): await websocket.close() +async def ws_dependency(): + return "Socket Dependency" + + [email protected]("/router-ws-depends/") +async def router_ws_decorator_depends( + websocket: WebSocket, data=Depends(ws_dependency) +): + await websocket.accept() + await websocket.send_text(data) + await websocket.close() + + app.include_router(router) app.include_router(prefix_router, prefix="/prefix") @@ -64,3 +77,16 @@ def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!" + + +def test_router_ws_depends(): + client = TestClient(app) + with client.websocket_connect("/router-ws-depends/") as websocket: + assert websocket.receive_text() == "Socket Dependency" + + +def test_router_ws_depends_with_override(): + client = TestClient(app) + app.dependency_overrides[ws_dependency] = lambda: "Override" + with client.websocket_connect("/router-ws-depends/") as websocket: + assert websocket.receive_text() == "Override"
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_ws_router.py F [100%] =================================== FAILURES =================================== _____________________ test_router_ws_depends_with_override _____________________ def test_router_ws_depends_with_override(): client = TestClient(app) app.dependency_overrides[ws_dependency] = lambda: "Override" with client.websocket_connect("/router-ws-depends/") as websocket: > assert websocket.receive_text() == "Override" E AssertionError: assert 'Socket Dependency' == 'Override' E - Override E + Socket Dependency tests/test_ws_router.py:92: AssertionError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_ws_router.py::test_router_ws_depends_with_override - Assert... ======================== 1 failed, 6 warnings in 2.09s =========================
pytest tests/test_ws_router.py::test_router_ws_depends_with_override
210af1fd3dc0f612a08fa02a0cb3f5adb81e5bfb
tests/test_ws_router.py
tiangolo__fastapi-3
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index b361048..b90935e 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -48,6 +48,28 @@ except ImportError: # pragma: nocover from pydantic.fields import Field as ModelField # type: ignore +def _prepare_response_content( + res: Any, *, by_alias: bool = True, exclude_unset: bool +) -> Any: + if isinstance(res, BaseModel): + if PYDANTIC_1: + return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) + else: + return res.dict( + by_alias=by_alias, skip_defaults=exclude_unset + ) # pragma: nocover + elif isinstance(res, list): + return [ + _prepare_response_content(item, exclude_unset=exclude_unset) for item in res + ] + elif isinstance(res, dict): + return { + k: _prepare_response_content(v, exclude_unset=exclude_unset) + for k, v in res.items() + } + return res + + async def serialize_response( *, field: ModelField = None, @@ -60,13 +82,9 @@ async def serialize_response( ) -> Any: if field: errors = [] - if exclude_unset and isinstance(response_content, BaseModel): - if PYDANTIC_1: - response_content = response_content.dict(exclude_unset=exclude_unset) - else: - response_content = response_content.dict( - skip_defaults=exclude_unset - ) # pragma: nocover + response_content = _prepare_response_content( + response_content, by_alias=by_alias, exclude_unset=exclude_unset + ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else:
pytest tests/test_serialize_response_model.py::test_validdict pytest tests/test_serialize_response_model.py::test_valid_exclude_unset pytest tests/test_serialize_response_model.py::test_coerce_exclude_unset pytest tests/test_serialize_response_model.py::test_validlist_exclude_unset pytest tests/test_serialize_response_model.py::test_validdict_exclude_unset RUN EVERY COMMAND 0 ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== __________________________________ test_valid __________________________________ def test_valid(): > response = client.get("/items/valid") tests/test_serialize_response_model.py:90: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 1 validation error for Item E response -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_valid - pydantic.error_wr... ======================== 1 failed, 6 warnings in 1.11s ========================= RUN EVERY COMMAND 1 pytest tests/test_serialize_response_model.py::test_valid ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== _________________________________ test_coerce __________________________________ def test_coerce(): > response = client.get("/items/coerce") tests/test_serialize_response_model.py:96: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 1 validation error for Item E response -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_coerce - pydantic.error_w... ======================== 1 failed, 6 warnings in 1.12s ========================= RUN EVERY COMMAND 2 pytest tests/test_serialize_response_model.py::test_coerce ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== ________________________________ test_validlist ________________________________ def test_validlist(): > response = client.get("/items/validlist") tests/test_serialize_response_model.py:106: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 3 validation errors for Item E response -> 0 -> aliased_name E field required (type=value_error.missing) E response -> 1 -> aliased_name E field required (type=value_error.missing) E response -> 2 -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_validlist - pydantic.erro... ======================== 1 failed, 6 warnings in 1.00s ========================= RUN EVERY COMMAND 3 pytest tests/test_serialize_response_model.py::test_validlist ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== ________________________________ test_validdict ________________________________ def test_validdict(): > response = client.get("/items/validdict") tests/test_serialize_response_model.py:116: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 3 validation errors for Item E response -> k1 -> aliased_name E field required (type=value_error.missing) E response -> k2 -> aliased_name E field required (type=value_error.missing) E response -> k3 -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_validdict - pydantic.erro... ======================== 1 failed, 6 warnings in 1.43s ========================= RUN EVERY COMMAND 4 pytest tests/test_serialize_response_model.py::test_validdict ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== ___________________________ test_valid_exclude_unset ___________________________ def test_valid_exclude_unset(): > response = client.get("/items/valid-exclude-unset") tests/test_serialize_response_model.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 1 validation error for Item E response -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_valid_exclude_unset - pyd... ======================== 1 failed, 6 warnings in 1.57s ========================= RUN EVERY COMMAND 5 pytest tests/test_serialize_response_model.py::test_valid_exclude_unset ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== __________________________ test_coerce_exclude_unset ___________________________ def test_coerce_exclude_unset(): > response = client.get("/items/coerce-exclude-unset") tests/test_serialize_response_model.py:132: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 1 validation error for Item E response -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_coerce_exclude_unset - py... ======================== 1 failed, 6 warnings in 1.77s ========================= RUN EVERY COMMAND 6 pytest tests/test_serialize_response_model.py::test_coerce_exclude_unset ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== _________________________ test_validlist_exclude_unset _________________________ def test_validlist_exclude_unset(): > response = client.get("/items/validlist-exclude-unset") tests/test_serialize_response_model.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 3 validation errors for Item E response -> 0 -> aliased_name E field required (type=value_error.missing) E response -> 1 -> aliased_name E field required (type=value_error.missing) E response -> 2 -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_validlist_exclude_unset ======================== 1 failed, 6 warnings in 1.60s ========================= RUN EVERY COMMAND 7 pytest tests/test_serialize_response_model.py::test_validlist_exclude_unset ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_serialize_response_model.py F [100%] =================================== FAILURES =================================== _________________________ test_validdict_exclude_unset _________________________ def test_validdict_exclude_unset(): > response = client.get("/items/validdict-exclude-unset") tests/test_serialize_response_model.py:148: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:413: in request return super().request( /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:243: in send raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/testclient.py:240: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() fastapi/applications.py:149: in __call__ await super().__call__(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/applications.py:102: in __call__ await self.middleware_stack(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:181: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/middleware/errors.py:159: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:82: in __call__ raise exc from None /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/exceptions.py:71: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:550: in __call__ await route.handle(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:227: in handle await self.app(scope, receive, send) /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/routing.py:155: in app response_data = await serialize_response( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_content.dict( skip_defaults=exclude_unset ) # pragma: nocover if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: > raise ValidationError(errors, field.type_) E pydantic.error_wrappers.ValidationError: 3 validation errors for Item E response -> k1 -> aliased_name E field required (type=value_error.missing) E response -> k2 -> aliased_name E field required (type=value_error.missing) E response -> k3 -> aliased_name E field required (type=value_error.missing) fastapi/routing.py:81: ValidationError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_serialize_response_model.py::test_validdict_exclude_unset ======================== 1 failed, 6 warnings in 1.70s =========================
pytest tests/test_serialize_response_model.py::test_valid pytest tests/test_serialize_response_model.py::test_coerce pytest tests/test_serialize_response_model.py::test_validlist pytest tests/test_serialize_response_model.py::test_validdict pytest tests/test_serialize_response_model.py::test_valid_exclude_unset pytest tests/test_serialize_response_model.py::test_coerce_exclude_unset pytest tests/test_serialize_response_model.py::test_validlist_exclude_unset pytest tests/test_serialize_response_model.py::test_validdict_exclude_unset
869c7389e22dc9ad659940fa271da76c4f3ba3b1
tests/test_serialize_response_model.py
tiangolo__fastapi-10
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index 3c6774c..930cbe0 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -52,6 +52,8 @@ def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) + if skip_defaults and isinstance(response, BaseModel): + value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=include,
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_skip_defaults.py F [100%] =================================== FAILURES =================================== _____________________________ test_return_defaults _____________________________ def test_return_defaults(): response = client.get("/") > assert response.json() == {"sub": {}} E AssertionError: assert {'sub': {'a':...'}, 'x': None} == {'sub': {}} E Differing items: E {'sub': {'a': 'foo'}} != {'sub': {}} E Left contains 1 more item: E {'x': None} E Use -v to get the full diff tests/test_skip_defaults.py:29: AssertionError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_skip_defaults.py::test_return_defaults - AssertionError: as... ======================== 1 failed, 7 warnings in 0.67s =========================
pytest tests/test_skip_defaults.py::test_return_defaults
b77a43bcac3ec8e7edbe82543e777c60ae85c178
tests/test_skip_defaults.py
tiangolo__fastapi-8
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index 8f61ea5..b090231 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -348,8 +348,10 @@ class APIRouter(routing.Router): include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, + route_class_override: Optional[Type[APIRoute]] = None, ) -> None: - route = self.route_class( + route_class = route_class_override or self.route_class + route = route_class( path, endpoint=endpoint, response_model=response_model, @@ -487,6 +489,7 @@ class APIRouter(routing.Router): include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, + route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route(
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_custom_route_class.py F [100%] =================================== FAILURES =================================== ______________________________ test_route_classes ______________________________ def test_route_classes(): routes = {} r: APIRoute for r in app.router.routes: routes[r.path] = r > assert routes["/a/"].x_type == "A" E AttributeError: 'APIRoute' object has no attribute 'x_type' tests/test_custom_route_class.py:112: AttributeError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_custom_route_class.py::test_route_classes - AttributeError:... ======================== 1 failed, 7 warnings in 1.59s =========================
pytest tests/test_custom_route_class.py::test_route_classes
fdb6d43e103bcf7a7325d796e37c9435c9460e4c
tests/test_custom_route_class.py
tiangolo__fastapi-15
tiangolo/fastapi
diff --git a/fastapi/routing.py b/fastapi/routing.py index 6d252d8..67619bd 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -271,6 +271,10 @@ class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) + elif isinstance(route, routing.WebSocketRoute): + self.add_websocket_route( + prefix + route.path, route.endpoint, name=route.name + ) def get( self,
0 ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_ws_router.py F [100%] =================================== FAILURES =================================== _________________________________ test_router __________________________________ def test_router(): client = TestClient(app) > with client.websocket_connect("/router") as websocket: tests/test_ws_router.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:436: in websocket_connect super().request("GET", url, **kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:140: in send session = WebSocketTestSession(self.app, scope) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:273: in __init__ self._raise_on_close(message) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <starlette.testclient.WebSocketTestSession object at 0x7fdce25e3f40> message = {'code': 1000, 'type': 'websocket.close'} def _raise_on_close(self, message: Message) -> None: if message["type"] == "websocket.close": > raise WebSocketDisconnect(message.get("code", 1000)) E starlette.websockets.WebSocketDisconnect: 1000 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:309: WebSocketDisconnect =============================== warnings summary =============================== /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.26') /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_ws_router.py::test_router - starlette.websockets.WebSocketD... ======================== 1 failed, 7 warnings in 0.89s ========================= RUN EVERY COMMAND 1 pytest tests/test_ws_router.py::test_router ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_ws_router.py F [100%] =================================== FAILURES =================================== ______________________________ test_prefix_router ______________________________ def test_prefix_router(): client = TestClient(app) > with client.websocket_connect("/prefix/") as websocket: tests/test_ws_router.py:51: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:436: in websocket_connect super().request("GET", url, **kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:140: in send session = WebSocketTestSession(self.app, scope) /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:273: in __init__ self._raise_on_close(message) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <starlette.testclient.WebSocketTestSession object at 0x7f178a692c70> message = {'code': 1000, 'type': 'websocket.close'} def _raise_on_close(self, message: Message) -> None: if message["type"] == "websocket.close": > raise WebSocketDisconnect(message.get("code", 1000)) E starlette.websockets.WebSocketDisconnect: 1000 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/starlette/testclient.py:309: WebSocketDisconnect =============================== warnings summary =============================== /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.26') /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_ws_router.py::test_prefix_router - starlette.websockets.Web... ======================== 1 failed, 7 warnings in 0.76s =========================
pytest tests/test_ws_router.py::test_router pytest tests/test_ws_router.py::test_prefix_router
b16ca54c30644667ab9f65a712704850666a039c
tests/test_ws_router.py
tiangolo__fastapi-11
tiangolo/fastapi
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 28c57c2..c898ab7 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -131,12 +131,17 @@ def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: - return ( + if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field.schema, params.Body) - ) + ): + return False + if field.sub_fields: + if not all(is_scalar_field(f) for f in field.sub_fields): + return False + return True def is_scalar_sequence_field(field: Field) -> bool:
pytest tests/test_union_inherited_body.py::test_inherited_item_openapi_schema pytest tests/test_union_inherited_body.py::test_post_extended_item pytest tests/test_union_inherited_body.py::test_post_item RUN EVERY COMMAND 0 ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_body.py F [100%] =================================== FAILURES =================================== ___________________________ test_item_openapi_schema ___________________________ def test_item_openapi_schema(): > response = client.get("/openapi.json") tests/test_union_body.py:110: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/applications.py:87: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:73: in openapi self.openapi_schema = get_openapi( fastapi/openapi/utils.py:254: in get_openapi result = get_openapi_path(route=route, model_name_map=model_name_map) fastapi/openapi/utils.py:162: in get_openapi_path validation_definitions, operation_parameters = get_openapi_operation_parameters( fastapi/openapi/utils.py:87: in get_openapi_operation_parameters "schema": field_schema(param, model_name_map={})[0], /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:297: in field_schema f_schema, f_definitions, f_nested_models = field_type_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:527: in field_type_schema f_schema, f_definitions, f_nested_models = field_singleton_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:742: in field_singleton_schema return field_singleton_sub_fields_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:648: in field_singleton_sub_fields_schema sub_schema, sub_definitions, sub_nested_models = field_type_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:527: in field_type_schema f_schema, f_definitions, f_nested_models = field_singleton_schema( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ field = <Field(item_OtherItem type=OtherItem required)> def field_singleton_schema( # noqa: C901 (ignore complexity) field: Field, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ This function is indirectly used by ``field_schema()``, you should probably be using that function. Take a single Pydantic ``Field``, and return its schema and any additional definitions from sub-models. """ ref_prefix = ref_prefix or default_prefix definitions: Dict[str, Any] = {} nested_models: Set[str] = set() if field.sub_fields: return field_singleton_sub_fields_schema( field.sub_fields, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) if field.type_ is Any or type(field.type_) == TypeVar: return {}, definitions, nested_models # no restrictions if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') f_schema: Dict[str, Any] = {} if field.schema is not None and field.schema.const: f_schema['const'] = field.default field_type = field.type_ if is_new_type(field_type): field_type = new_type_supertype(field_type) if is_literal_type(field_type): # If there were multiple literal values, field.sub_fields would not be falsy literal_value = literal_values(field_type)[0] field_type = type(literal_value) f_schema['const'] = literal_value if issubclass(field_type, Enum): f_schema.update({'enum': [item.value for item in field_type]}) # Don't return immediately, to allow adding specific types for field_name, schema_name in validation_attribute_to_schema_keyword.items(): field_value = getattr(field_type, field_name, None) if field_value is not None: if field_name == 'regex': field_value = field_value.pattern f_schema[schema_name] = field_value for type_, t_schema in field_class_to_schema_enum_enabled: if issubclass(field_type, type_): f_schema.update(t_schema) break # Return schema, with or without enum definitions if f_schema: return f_schema, definitions, nested_models for type_, t_schema in field_class_to_schema_enum_disabled: if issubclass(field_type, type_): return t_schema, definitions, nested_models # Handle dataclass-based models if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), pydantic.BaseModel): field_type = field_type.__pydantic_model__ # type: ignore if issubclass(field_type, pydantic.BaseModel): > model_name = model_name_map[field_type] E KeyError: <class 'tests.test_union_body.OtherItem'> /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:788: KeyError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_body.py::test_item_openapi_schema - KeyError: <class ... ======================== 1 failed, 7 warnings in 0.91s ========================= RUN EVERY COMMAND 1 pytest tests/test_union_body.py::test_item_openapi_schema ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_body.py F [100%] =================================== FAILURES =================================== _____________________________ test_post_other_item _____________________________ def test_post_other_item(): > response = client.post("/items/", json={"price": 100}) tests/test_union_body.py:116: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:578: in post return self.request('POST', url, data=data, json=json, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ request = <starlette.requests.Request object at 0x7fcc65db13d0> async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: > raise RequestValidationError(errors) E TypeError: __init__() missing 1 required positional argument: 'model' fastapi/routing.py:105: TypeError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_body.py::test_post_other_item - TypeError: __init__()... ======================== 1 failed, 7 warnings in 0.51s ========================= RUN EVERY COMMAND 2 pytest tests/test_union_body.py::test_post_other_item ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_body.py F [100%] =================================== FAILURES =================================== ________________________________ test_post_item ________________________________ def test_post_item(): > response = client.post("/items/", json={"name": "Foo"}) tests/test_union_body.py:122: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:578: in post return self.request('POST', url, data=data, json=json, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ request = <starlette.requests.Request object at 0x7f062e400400> async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: > raise RequestValidationError(errors) E TypeError: __init__() missing 1 required positional argument: 'model' fastapi/routing.py:105: TypeError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_body.py::test_post_item - TypeError: __init__() missi... ======================== 1 failed, 7 warnings in 0.68s ========================= RUN EVERY COMMAND 3 pytest tests/test_union_body.py::test_post_item ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_inherited_body.py F [100%] =================================== FAILURES =================================== ______________________ test_inherited_item_openapi_schema ______________________ @skip_py36 def test_inherited_item_openapi_schema(): > response = client.get("/openapi.json") tests/test_union_inherited_body.py:124: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:543: in get return self.request('GET', url, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) fastapi/applications.py:87: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:73: in openapi self.openapi_schema = get_openapi( fastapi/openapi/utils.py:254: in get_openapi result = get_openapi_path(route=route, model_name_map=model_name_map) fastapi/openapi/utils.py:162: in get_openapi_path validation_definitions, operation_parameters = get_openapi_operation_parameters( fastapi/openapi/utils.py:87: in get_openapi_operation_parameters "schema": field_schema(param, model_name_map={})[0], /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:297: in field_schema f_schema, f_definitions, f_nested_models = field_type_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:527: in field_type_schema f_schema, f_definitions, f_nested_models = field_singleton_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:742: in field_singleton_schema return field_singleton_sub_fields_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:648: in field_singleton_sub_fields_schema sub_schema, sub_definitions, sub_nested_models = field_type_schema( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:527: in field_type_schema f_schema, f_definitions, f_nested_models = field_singleton_schema( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ field = <Field(item_ExtendedItem type=ExtendedItem required)> def field_singleton_schema( # noqa: C901 (ignore complexity) field: Field, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ This function is indirectly used by ``field_schema()``, you should probably be using that function. Take a single Pydantic ``Field``, and return its schema and any additional definitions from sub-models. """ ref_prefix = ref_prefix or default_prefix definitions: Dict[str, Any] = {} nested_models: Set[str] = set() if field.sub_fields: return field_singleton_sub_fields_schema( field.sub_fields, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) if field.type_ is Any or type(field.type_) == TypeVar: return {}, definitions, nested_models # no restrictions if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') f_schema: Dict[str, Any] = {} if field.schema is not None and field.schema.const: f_schema['const'] = field.default field_type = field.type_ if is_new_type(field_type): field_type = new_type_supertype(field_type) if is_literal_type(field_type): # If there were multiple literal values, field.sub_fields would not be falsy literal_value = literal_values(field_type)[0] field_type = type(literal_value) f_schema['const'] = literal_value if issubclass(field_type, Enum): f_schema.update({'enum': [item.value for item in field_type]}) # Don't return immediately, to allow adding specific types for field_name, schema_name in validation_attribute_to_schema_keyword.items(): field_value = getattr(field_type, field_name, None) if field_value is not None: if field_name == 'regex': field_value = field_value.pattern f_schema[schema_name] = field_value for type_, t_schema in field_class_to_schema_enum_enabled: if issubclass(field_type, type_): f_schema.update(t_schema) break # Return schema, with or without enum definitions if f_schema: return f_schema, definitions, nested_models for type_, t_schema in field_class_to_schema_enum_disabled: if issubclass(field_type, type_): return t_schema, definitions, nested_models # Handle dataclass-based models if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), pydantic.BaseModel): field_type = field_type.__pydantic_model__ # type: ignore if issubclass(field_type, pydantic.BaseModel): > model_name = model_name_map[field_type] E KeyError: <class 'tests.test_union_inherited_body.ExtendedItem'> /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/schema.py:788: KeyError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_inherited_body.py::test_inherited_item_openapi_schema ======================== 1 failed, 7 warnings in 0.69s ========================= RUN EVERY COMMAND 4 pytest tests/test_union_inherited_body.py::test_inherited_item_openapi_schema ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_inherited_body.py F [100%] =================================== FAILURES =================================== ___________________________ test_post_extended_item ____________________________ @skip_py36 def test_post_extended_item(): > response = client.post("/items/", json={"name": "Foo", "age": 5}) tests/test_union_inherited_body.py:131: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:578: in post return self.request('POST', url, data=data, json=json, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ request = <starlette.requests.Request object at 0x7efcbb416550> async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: > raise RequestValidationError(errors) E TypeError: __init__() missing 1 required positional argument: 'model' fastapi/routing.py:105: TypeError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_inherited_body.py::test_post_extended_item - TypeErro... ======================== 1 failed, 7 warnings in 1.03s ========================= RUN EVERY COMMAND 5 pytest tests/test_union_inherited_body.py::test_post_extended_item ============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_union_inherited_body.py F [100%] =================================== FAILURES =================================== ________________________________ test_post_item ________________________________ @skip_py36 def test_post_item(): > response = client.post("/items/", json={"name": "Foo"}) tests/test_union_inherited_body.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:578: in post return self.request('POST', url, data=data, json=json, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:405: in request return super().request( /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:530: in request resp = self.send(prep, **send_kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/requests/sessions.py:643: in send r = adapter.send(request, **kwargs) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:238: in send raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/asyncio/base_events.py:616: in run_until_complete return future.result() /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/applications.py:133: in __call__ await self.error_middleware(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:177: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/middleware/errors.py:155: in __call__ await self.app(scope, receive, _send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:73: in __call__ raise exc from None /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/exceptions.py:62: in __call__ await self.app(scope, receive, sender) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:590: in __call__ await route(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:208: in __call__ await self.app(scope, receive, send) /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/starlette/routing.py:41: in app response = await func(request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ request = <starlette.requests.Request object at 0x7f8ccbcc0580> async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: > raise RequestValidationError(errors) E TypeError: __init__() missing 1 required positional argument: 'model' fastapi/routing.py:105: TypeError =============================== warnings summary =============================== /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.32.2') /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6a8345d79f511e631e8d83e9f190ff61/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_union_inherited_body.py::test_post_item - TypeError: __init... ======================== 1 failed, 7 warnings in 0.84s =========================
pytest tests/test_union_body.py::test_item_openapi_schema pytest tests/test_union_body.py::test_post_other_item pytest tests/test_union_body.py::test_post_item pytest tests/test_union_inherited_body.py::test_inherited_item_openapi_schema pytest tests/test_union_inherited_body.py::test_post_extended_item pytest tests/test_union_inherited_body.py::test_post_item
bf229ad5d830eb5320f966d51a55e590e8d57008
tests/test_union_body.py;tests/test_union_inherited_body.py
tiangolo__fastapi-14
tiangolo/fastapi
diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 6572c7c..a045bdf 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -99,7 +99,7 @@ class SchemaBase(BaseModel): not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore items: Optional[Any] = None properties: Optional[Dict[str, Any]] = None - additionalProperties: Optional[Union[bool, Any]] = None + additionalProperties: Optional[Union[Dict[str, Any], bool]] = None description: Optional[str] = None format: Optional[str] = None default: Optional[Any] = None @@ -120,7 +120,7 @@ class Schema(SchemaBase): not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore items: Optional[SchemaBase] = None properties: Optional[Dict[str, SchemaBase]] = None - additionalProperties: Optional[Union[bool, SchemaBase]] = None + additionalProperties: Optional[Union[SchemaBase, bool]] = None class Example(BaseModel): @@ -220,7 +220,7 @@ class Operation(BaseModel): operationId: Optional[str] = None parameters: Optional[List[Union[Parameter, Reference]]] = None requestBody: Optional[Union[RequestBody, Reference]] = None - responses: Union[Responses, Dict[Union[str], Response]] + responses: Union[Responses, Dict[str, Response]] # Workaround OpenAPI recursive reference callbacks: Optional[Dict[str, Union[Dict[str, Any], Reference]]] = None deprecated: Optional[bool] = None
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_additional_properties.py F [100%] =================================== FAILURES =================================== ______________________ test_additional_properties_schema _______________________ def test_additional_properties_schema(): response = client.get("/openapi.json") assert response.status_code == 200 > assert response.json() == openapi_schema E AssertionError: assert {'components'...'Foo Post'}}}} == {'components'...'Foo Post'}}}} E Omitting 3 identical items, use -vv to show E Differing items: E {'components': {'schemas': {'HTTPValidationError': {'properties': {'detail': {'items': {...}, 'title': 'Detail', 'type... 'Error Type', 'type': 'string'}}, 'required': ['loc', 'msg', 'type'], 'title': 'ValidationError', 'type': 'object'}}}} != {'components': {'schemas': {'HTTPValidationError': {'properties': {'detail': {'items': {...}, 'title': 'Detail', 'type... 'Error Type', 'type': 'string'}}, 'required': ['loc', 'msg', 'type'], 'title': 'ValidationError', 'type': 'object'}}}} E Use -v to get the full diff tests/test_additional_properties.py:104: AssertionError =============================== warnings summary =============================== /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.26') /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/235ca55b977721137e676add71d64e98/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_additional_properties.py::test_additional_properties_schema ======================== 1 failed, 7 warnings in 0.74s =========================
pytest tests/test_additional_properties.py::test_additional_properties_schema
2ddb804940bbcad4ed730b2a910c8fd3c1167127
tests/test_additional_properties.py
tiangolo__fastapi-5
tiangolo/fastapi
diff --git a/fastapi/utils.py b/fastapi/utils.py index a068cc5..6a0c1bf 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -97,7 +97,7 @@ def create_cloned_field(field: ModelField) -> ModelField: original_type.__name__, __config__=original_type.__config__ ) for f in original_type.__fields__.values(): - use_type.__fields__[f.name] = f + use_type.__fields__[f.name] = create_cloned_field(f) use_type.__validators__ = original_type.__validators__ if PYDANTIC_1: new_field = ModelField(
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_filter_pydantic_sub_model.py F [100%] =================================== FAILURES =================================== ____________________________ test_filter_sub_model _____________________________ def test_filter_sub_model(): response = client.get("/model") assert response.status_code == 200 > assert response.json() == { "name": "model-a-name", "description": "model-a-desc", "model_b": {"username": "test-user"}, } E AssertionError: assert {'description...model-a-name'} == {'description...model-a-name'} E Omitting 2 identical items, use -vv to show E Differing items: E {'model_b': {'password': 'test-password', 'username': 'test-user'}} != {'model_b': {'username': 'test-user'}} E Use -v to get the full diff tests/test_filter_pydantic_sub_model.py:87: AssertionError =============================== warnings summary =============================== /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/e22995067de84b5655026e5ebb62b5bf/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_filter_pydantic_sub_model.py::test_filter_sub_model - Asser... ======================== 1 failed, 6 warnings in 0.62s =========================
pytest tests/test_filter_pydantic_sub_model.py::test_filter_sub_model
7cea84b74ca3106a7f861b774e9d215e5228728f
tests/test_filter_pydantic_sub_model.py
tiangolo__fastapi-16
tiangolo/fastapi
diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 82e3ffa..f5059a7 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -15,17 +15,12 @@ def jsonable_encoder( custom_encoder: dict = {}, ) -> Any: if isinstance(obj, BaseModel): - if not obj.Config.json_encoders: - return jsonable_encoder( - obj.dict(include=include, exclude=exclude, by_alias=by_alias), - include_none=include_none, - ) - else: - return jsonable_encoder( - obj.dict(include=include, exclude=exclude, by_alias=by_alias), - include_none=include_none, - custom_encoder=obj.Config.json_encoders, - ) + encoder = getattr(obj.Config, "json_encoders", custom_encoder) + return jsonable_encoder( + obj.dict(include=include, exclude=exclude, by_alias=by_alias), + include_none=include_none, + custom_encoder=encoder, + ) if isinstance(obj, Enum): return obj.value if isinstance(obj, (str, int, float, type(None))):
diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 9108df9d..92eb34a7 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -1,5 +1,9 @@ +from datetime import datetime, timezone +from enum import Enum + import pytest from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel class Person: @@ -32,6 +36,29 @@ class Unserializable: raise NotImplementedError() +class ModelWithCustomEncoder(BaseModel): + dt_field: datetime + + class Config: + json_encoders = { + datetime: lambda dt: dt.replace( + microsecond=0, tzinfo=timezone.utc + ).isoformat() + } + + +class RoleEnum(Enum): + admin = "admin" + normal = "normal" + + +class ModelWithConfig(BaseModel): + role: RoleEnum = None + + class Config: + use_enum_values = True + + def test_encode_class(): person = Person(name="Foo") pet = Pet(owner=person, name="Firulais") @@ -48,3 +75,13 @@ def test_encode_unsupported(): unserializable = Unserializable() with pytest.raises(ValueError): jsonable_encoder(unserializable) + + +def test_encode_custom_json_encoders_model(): + model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) + assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} + + +def test_encode_model_with_config(): + model = ModelWithConfig(role=RoleEnum.admin) + assert jsonable_encoder(model) == {"role": "admin"}
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_jsonable_encoder.py F [100%] =================================== FAILURES =================================== ________________________ test_encode_model_with_config _________________________ def test_encode_model_with_config(): model = ModelWithConfig(role=RoleEnum.admin) > assert jsonable_encoder(model) == {"role": "admin"} tests/test_jsonable_encoder.py:87: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ obj = <ModelWithConfig role='admin'>, include = None, exclude = set() by_alias = False, include_none = True, custom_encoder = {} def jsonable_encoder( obj: Any, include: Set[str] = None, exclude: Set[str] = set(), by_alias: bool = False, include_none: bool = True, custom_encoder: dict = {}, ) -> Any: if isinstance(obj, BaseModel): > if not obj.Config.json_encoders: E AttributeError: type object 'Config' has no attribute 'json_encoders' fastapi/encoders.py:18: AttributeError =============================== warnings summary =============================== /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/pydantic/version.py:5 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/pydantic/version.py:5: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. VERSION = StrictVersion('0.18.2') /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/f25ec32b84fa2c9f65b9ad23b80f6958/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_jsonable_encoder.py::test_encode_model_with_config - Attrib... ======================== 1 failed, 7 warnings in 0.65s =========================
pytest tests/test_jsonable_encoder.py::test_encode_model_with_config
92c825be6a7362099400c9c3fe8b01ea13add3dc
tests/test_datetime_custom_encoder.py;tests/test_jsonable_encoder.py
tiangolo__fastapi-1
tiangolo/fastapi
diff --git a/fastapi/applications.py b/fastapi/applications.py index 8270e54..84a1b6d 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -171,6 +171,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -197,6 +199,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -222,6 +226,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -250,6 +256,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -309,6 +317,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -334,6 +344,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -359,6 +371,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -384,6 +398,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -409,6 +425,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -434,6 +452,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -459,6 +479,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -484,6 +506,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -509,6 +533,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -534,6 +560,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -559,6 +587,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -584,6 +614,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -609,6 +641,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -634,6 +668,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -659,6 +695,8 @@ class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -684,6 +722,8 @@ class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, diff --git a/fastapi/encoders.py b/fastapi/encoders.py index ae4794b..26ceb21 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -34,7 +34,8 @@ def jsonable_encoder( by_alias: bool = True, skip_defaults: bool = None, exclude_unset: bool = False, - include_none: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, custom_encoder: dict = {}, sqlalchemy_safe: bool = True, ) -> Any: @@ -58,8 +59,12 @@ def jsonable_encoder( exclude=exclude, by_alias=by_alias, exclude_unset=bool(exclude_unset or skip_defaults), + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, ) else: # pragma: nocover + if exclude_defaults: + raise ValueError("Cannot use exclude_defaults") obj_dict = obj.dict( include=include, exclude=exclude, @@ -68,7 +73,8 @@ def jsonable_encoder( ) return jsonable_encoder( obj_dict, - include_none=include_none, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, custom_encoder=encoder, sqlalchemy_safe=sqlalchemy_safe, ) @@ -87,14 +93,14 @@ def jsonable_encoder( or (not isinstance(key, str)) or (not key.startswith("_sa")) ) - and (value is not None or include_none) + and (value is not None or not exclude_none) and ((include and key in include) or key not in exclude) ): encoded_key = jsonable_encoder( key, by_alias=by_alias, exclude_unset=exclude_unset, - include_none=include_none, + exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) @@ -102,7 +108,7 @@ def jsonable_encoder( value, by_alias=by_alias, exclude_unset=exclude_unset, - include_none=include_none, + exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) @@ -118,7 +124,8 @@ def jsonable_encoder( exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, - include_none=include_none, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) @@ -153,7 +160,8 @@ def jsonable_encoder( data, by_alias=by_alias, exclude_unset=exclude_unset, - include_none=include_none, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 91f90ec..c1e66fc 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -81,7 +81,7 @@ def get_openapi_security_definitions(flat_dependant: Dependant) -> Tuple[Dict, L security_definition = jsonable_encoder( security_requirement.security_scheme.model, by_alias=True, - include_none=False, + exclude_none=True, ) security_name = security_requirement.security_scheme.scheme_name security_definitions[security_name] = security_definition @@ -310,4 +310,4 @@ def get_openapi( if components: output["components"] = components output["paths"] = paths - return jsonable_encoder(OpenAPI(**output), by_alias=True, include_none=False) + return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) diff --git a/fastapi/routing.py b/fastapi/routing.py index 1ec0b69..3ac420e 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -49,22 +49,43 @@ except ImportError: # pragma: nocover def _prepare_response_content( - res: Any, *, by_alias: bool = True, exclude_unset: bool + res: Any, + *, + by_alias: bool = True, + exclude_unset: bool, + exclude_defaults: bool = False, + exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: - return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) + return res.dict( + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) else: return res.dict( - by_alias=by_alias, skip_defaults=exclude_unset + by_alias=by_alias, skip_defaults=exclude_unset, ) # pragma: nocover elif isinstance(res, list): return [ - _prepare_response_content(item, exclude_unset=exclude_unset) for item in res + _prepare_response_content( + item, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + for item in res ] elif isinstance(res, dict): return { - k: _prepare_response_content(v, exclude_unset=exclude_unset) + k: _prepare_response_content( + v, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) for k, v in res.items() } return res @@ -78,12 +99,18 @@ async def serialize_response( exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( - response_content, by_alias=by_alias, exclude_unset=exclude_unset + response_content, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) @@ -103,6 +130,8 @@ async def serialize_response( exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, ) else: return jsonable_encoder(response_content) @@ -131,6 +160,8 @@ def get_request_handler( response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" @@ -177,6 +208,8 @@ def get_request_handler( exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, ) response = response_class( @@ -255,6 +288,8 @@ class APIRoute(routing.Route): response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, @@ -326,6 +361,8 @@ class APIRoute(routing.Route): self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_exclude_unset = response_model_exclude_unset + self.response_model_exclude_defaults = response_model_exclude_defaults + self.response_model_exclude_none = response_model_exclude_none self.include_in_schema = include_in_schema self.response_class = response_class @@ -352,6 +389,8 @@ class APIRoute(routing.Route): response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_exclude_unset=self.response_model_exclude_unset, + response_model_exclude_defaults=self.response_model_exclude_defaults, + response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, ) @@ -400,6 +439,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -429,6 +470,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -457,6 +500,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -486,6 +531,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -560,6 +607,8 @@ class APIRouter(routing.Router): response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, + response_model_exclude_defaults=route.response_model_exclude_defaults, + response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, @@ -606,6 +655,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -632,6 +683,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -657,6 +710,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -683,6 +738,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -708,6 +765,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -734,6 +793,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -759,6 +820,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -785,6 +848,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -810,6 +875,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -836,6 +903,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -861,6 +930,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -887,6 +958,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -912,6 +985,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -938,6 +1013,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, @@ -963,6 +1040,8 @@ class APIRouter(routing.Router): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, @@ -989,6 +1068,8 @@ class APIRouter(routing.Router): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, diff --git a/tests/test_skip_defaults.py b/tests/test_skip_defaults.py index c9a85a3..ed84df6 100644 --- a/tests/test_skip_defaults.py +++ b/tests/test_skip_defaults.py @@ -18,11 +18,53 @@ class Model(BaseModel): class ModelSubclass(Model): y: int + z: int = 0 + w: int = None + + +class ModelDefaults(BaseModel): + w: Optional[str] = None + x: Optional[str] = None + y: str = "y" + z: str = "z" @app.get("/", response_model=Model, response_model_exclude_unset=True) def get() -> ModelSubclass: - return ModelSubclass(sub={}, y=1) + return ModelSubclass(sub={}, y=1, z=0) + + [email protected]( + "/exclude_unset", response_model=ModelDefaults, response_model_exclude_unset=True +) +def get() -> ModelDefaults: + return ModelDefaults(x=None, y="y") + + [email protected]( + "/exclude_defaults", + response_model=ModelDefaults, + response_model_exclude_defaults=True, +) +def get() -> ModelDefaults: + return ModelDefaults(x=None, y="y") + + [email protected]( + "/exclude_none", response_model=ModelDefaults, response_model_exclude_none=True +) +def get() -> ModelDefaults: + return ModelDefaults(x=None, y="y") + + [email protected]( + "/exclude_unset_none", + response_model=ModelDefaults, + response_model_exclude_unset=True, + response_model_exclude_none=True, +) +def get() -> ModelDefaults: + return ModelDefaults(x=None, y="y") client = TestClient(app) @@ -31,3 +73,23 @@ client = TestClient(app) def test_return_defaults(): response = client.get("/") assert response.json() == {"sub": {}} + + +def test_return_exclude_unset(): + response = client.get("/exclude_unset") + assert response.json() == {"x": None, "y": "y"} + + +def test_return_exclude_defaults(): + response = client.get("/exclude_defaults") + assert response.json() == {} + + +def test_return_exclude_none(): + response = client.get("/exclude_none") + assert response.json() == {"y": "y", "z": "z"} + + +def test_return_exclude_unset_none(): + response = client.get("/exclude_unset_none") + assert response.json() == {"y": "y"}
diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index f94771aa..adee443a 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -70,6 +70,12 @@ class ModelWithAlias(BaseModel): foo: str = Field(..., alias="Foo") +class ModelWithDefault(BaseModel): + foo: str = ... + bar: str = "bar" + bla: str = "bla" + + @pytest.fixture( name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath] ) @@ -121,6 +127,16 @@ def test_encode_model_with_alias(): assert jsonable_encoder(model) == {"Foo": "Bar"} +def test_encode_model_with_default(): + model = ModelWithDefault(foo="foo", bar="bar") + assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"} + assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"} + assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"} + assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == { + "foo": "foo" + } + + def test_custom_encoders(): class safe_datetime(datetime): pass
============================= test session starts ============================== platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/fastapi plugins: cov-2.9.0 collected 1 item tests/test_jsonable_encoder.py F [100%] =================================== FAILURES =================================== ________________________ test_encode_model_with_default ________________________ def test_encode_model_with_default(): model = ModelWithDefault(foo="foo", bar="bar") assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"} assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"} > assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"} E TypeError: jsonable_encoder() got an unexpected keyword argument 'exclude_defaults' tests/test_jsonable_encoder.py:134: TypeError =============================== warnings summary =============================== /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10 /opt/conda/envs/6d77396cd44c7df1384dad69b48c4335/lib/python3.8/site-packages/aiofiles/os.py:10: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead def run(*args, loop=None, executor=None, **kwargs): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_jsonable_encoder.py::test_encode_model_with_default - TypeE... ======================== 1 failed, 6 warnings in 1.72s =========================
pytest tests/test_jsonable_encoder.py::test_encode_model_with_default
766157bfb4e7dfccba09ab398e8ec444d14e947c
tests/test_jsonable_encoder.py
jakubroztocil__httpie-4
jakubroztocil/httpie
diff --git a/httpie/models.py b/httpie/models.py index f6b9dff..af6163f 100644 --- a/httpie/models.py +++ b/httpie/models.py @@ -102,8 +102,7 @@ class HTTPRequest(HTTPMessage): ) headers = dict(self._orig.headers) - - if 'Host' not in headers: + if 'Host' not in self._orig.headers: headers['Host'] = url.netloc.split('@')[-1] headers = ['%s: %s' % (name, value)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/httpie plugins: httpbin-1.0.0 collected 1 item tests/test_regressions.py F [100%] =================================== FAILURES =================================== __________________________ test_Host_header_overwrite __________________________ def test_Host_header_overwrite(): """ https://github.com/jakubroztocil/httpie/issues/235 """ host = 'httpbin.org' url = 'http://{httpbin_ip}/get'.format( httpbin_ip=socket.gethostbyname(host)) r = http('--print=hH', url, 'host:{}'.format(host)) assert HTTP_OK in r > assert r.lower().count('host:') == 1 E assert 2 == 1 E + where 2 = <built-in method count of str object at 0x7f545bfffdb0>('host:') E + where <built-in method count of str object at 0x7f545bfffdb0> = "get /get http/1.1\r\naccept: */*\r\naccept-encoding: gzip, deflate, compress\r\nhost: 54.211.216.104\r\nuser-agent: b...ength: 311\r\ncontent-type: application/json\r\ndate: sat, 15 jul 2023 13:10:23 gmt\r\nserver: gunicorn/19.9.0\r\n\r\n".count E + where "get /get http/1.1\r\naccept: */*\r\naccept-encoding: gzip, deflate, compress\r\nhost: 54.211.216.104\r\nuser-agent: b...ength: 311\r\ncontent-type: application/json\r\ndate: sat, 15 jul 2023 13:10:23 gmt\r\nserver: gunicorn/19.9.0\r\n\r\n" = <built-in method lower of StrCLIResponse object at 0x7f545bfd4138>() E + where <built-in method lower of StrCLIResponse object at 0x7f545bfd4138> = "GET /get HTTP/1.1\r\nAccept: */*\r\nAccept-Encoding: gzip, deflate, compress\r\nHost: 54.211.216.104\r\nUser-Agent: b...ength: 311\r\nContent-Type: application/json\r\nDate: Sat, 15 Jul 2023 13:10:23 GMT\r\nServer: gunicorn/19.9.0\r\n\r\n".lower tests/test_regressions.py:17: AssertionError =============================== warnings summary =============================== /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8: DeprecationWarning: invalid escape sequence \? /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:56: DeprecationWarning: invalid escape sequence \d /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/downloads.py:57: DeprecationWarning: invalid escape sequence \* /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/input.py:446 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/input.py:446 /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/httpie-0.9.0.dev0-py3.7.egg/httpie/input.py:446: DeprecationWarning: invalid escape sequence \= tests/test_regressions.py::test_Host_header_overwrite /opt/conda/envs/d67214fd79125c3eb272eee3600f4a34/lib/python3.7/site-packages/requests/models.py:153: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if isinstance(hook, collections.Callable): -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_regressions.py::test_Host_header_overwrite - assert 2 == 1 ======================== 1 failed, 9 warnings in 3.47s =========================
pytest tests/test_regressions.py::test_Host_header_overwrite
8c892edd4fe700a7ca5cc733dcb4817831d253e2
tests/test_regressions.py
jakubroztocil__httpie-2
jakubroztocil/httpie
diff --git a/httpie/client.py b/httpie/client.py index 1115f4d..482f9dc 100644 --- a/httpie/client.py +++ b/httpie/client.py @@ -40,6 +40,7 @@ def get_response(args, config_dir): """Send the request and return a `request.Response`.""" requests_session = get_requests_session() + requests_session.max_redirects = args.max_redirects if not args.session and not args.session_read_only: kwargs = get_requests_kwargs(args) diff --git a/httpie/core.py b/httpie/core.py index c0014ce..3dbe7f2 100644 --- a/httpie/core.py +++ b/httpie/core.py @@ -192,7 +192,6 @@ def main(args=sys.argv[1:], env=Environment(), error=None): error('Too many redirects (--max-redirects=%s).', args.max_redirects) except Exception as e: # TODO: Better distinction between expected and unexpected errors. - # Network errors vs. bugs, etc. if traceback: raise msg = str(e)
diff --git a/tests/test_redirects.py b/tests/test_redirects.py index 35cf9b0..94b1fc0 100644 --- a/tests/test_redirects.py +++ b/tests/test_redirects.py @@ -17,6 +17,6 @@ class TestRedirects: assert HTTP_OK in r def test_max_redirects(self, httpbin): - r = http('--max-redirects=2', '--follow', httpbin.url + '/redirect/3', + r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3', error_exit_ok=True) assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/httpie, inifile: pytest.ini plugins: httpbin-1.0.0 collected 1 item tests/test_redirects.py F [100%] =================================== FAILURES =================================== _______________________ TestRedirects.test_max_redirects _______________________ Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/httpie/tests/test_redirects.py", line 22, in test_max_redirects assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS AssertionError: assert 0 == 6 + where 0 = 'HTTP/1.1 200 OK\r\nAccess-Control-Allow-Credentials: true\r\nAccess-Control-Allow-Origin: *\r\nConnection: Close\r\nC... "User-Agent": "HTTPie/1.0.0-dev"\n },\n "origin": "127.0.0.1",\n "url": "http://127.0.0.1:45661/get"\n}\n\n'.exit_status + and 6 = ExitStatus.ERROR_TOO_MANY_REDIRECTS ----------------------------- Captured stderr call ----------------------------- 127.0.0.1 - - [15/Jul/2023 03:34:52] "GET /redirect/3 HTTP/1.1" 302 247 127.0.0.1 - - [15/Jul/2023 03:34:52] "GET /relative-redirect/2 HTTP/1.1" 302 0 127.0.0.1 - - [15/Jul/2023 03:34:52] "GET /relative-redirect/1 HTTP/1.1" 302 0 127.0.0.1 - - [15/Jul/2023 03:34:52] "GET /get HTTP/1.1" 200 212 =============================== warnings summary =============================== /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8: DeprecationWarning: invalid escape sequence \? /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56: DeprecationWarning: invalid escape sequence \d /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57: DeprecationWarning: invalid escape sequence \* /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463: DeprecationWarning: invalid escape sequence \= /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:11 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:11: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_redirects.py::TestRedirects::test_max_redirects - assert 0 ... ======================== 1 failed, 9 warnings in 1.48s =========================
pytest tests/test_redirects.py::TestRedirects::test_max_redirects
356e0436510fee70b4071fac58be81c0a0a7db59
tests/test_redirects.py
jakubroztocil__httpie-3
jakubroztocil/httpie
diff --git a/httpie/sessions.py b/httpie/sessions.py index e61a8e3..32254bf 100644 --- a/httpie/sessions.py +++ b/httpie/sessions.py @@ -101,6 +101,10 @@ class Session(BaseConfigDict): """ for name, value in request_headers.items(): + + if value is None: + continue # Ignore explicitely unset headers + value = value.decode('utf8') if name == 'User-Agent' and value.startswith('HTTPie/'): continue
diff --git a/tests/test_sessions.py b/tests/test_sessions.py index 966d87b..f568377 100644 --- a/tests/test_sessions.py +++ b/tests/test_sessions.py @@ -2,6 +2,7 @@ import os import shutil import sys +from tempfile import gettempdir import pytest @@ -174,3 +175,14 @@ class TestSession(SessionTestBase): r2 = http('--session=test', httpbin.url + '/headers', env=self.env()) assert HTTP_OK in r2 assert r2.json['headers']['User-Agent'] == 'custom' + + def test_download_in_session(self, httpbin): + # https://github.com/jkbrzt/httpie/issues/412 + self.start_session(httpbin) + cwd = os.getcwd() + try: + os.chdir(gettempdir()) + http('--session=test', '--download', + httpbin.url + '/get', env=self.env()) + finally: + os.chdir(cwd)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/httpie, inifile: pytest.ini plugins: httpbin-1.0.0 collected 1 item tests/test_sessions.py F [100%] =================================== FAILURES =================================== _____________________ TestSession.test_download_in_session _____________________ Traceback (most recent call last): File "/home/user/BugsInPy/temp/projects/httpie/tests/test_sessions.py", line 186, in test_download_in_session httpbin.url + '/get', env=self.env()) File "/home/user/BugsInPy/temp/projects/httpie/tests/utils.py", line 136, in http exit_status = main(args=args, **kwargs) File "/opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/core.py", line 115, in main response = get_response(args, config_dir=env.config.directory) File "/opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/client.py", line 55, in get_response read_only=bool(args.session_read_only), File "/opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/sessions.py", line 52, in get_response session.update_headers(kwargs['headers']) File "/opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/sessions.py", line 104, in update_headers value = value.decode('utf8') AttributeError: 'NoneType' object has no attribute 'decode' =============================== warnings summary =============================== /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/output/formatters/xml.py:8: DeprecationWarning: invalid escape sequence \? /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:56: DeprecationWarning: invalid escape sequence \d /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py:57: DeprecationWarning: invalid escape sequence \* /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:463: DeprecationWarning: invalid escape sequence \= /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:11 /opt/conda/envs/6b298c1f8a21a3e606bfa2fcf2e1c0e6/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/input.py:11: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ FAILED tests/test_sessions.py::TestSession::test_download_in_session - Attrib... ======================== 1 failed, 9 warnings in 1.32s =========================
pytest tests/test_sessions.py::TestSession::test_download_in_session
8c33e5e3d31d3cd6476c4d9bc963a4c529f883d2
tests/test_sessions.py
jakubroztocil__httpie-5
jakubroztocil/httpie
diff --git a/httpie/cli.py b/httpie/cli.py index 22797a5..29a55f6 100644 --- a/httpie/cli.py +++ b/httpie/cli.py @@ -36,14 +36,24 @@ class KeyValueType(object): """A type used with `argparse`.""" def __init__(self, *separators): self.separators = separators + self.escapes = ['\\\\' + sep for sep in separators] def __call__(self, string): found = {} + found_escapes = [] + for esc in self.escapes: + found_escapes += [m.span() for m in re.finditer(esc, string)] for sep in self.separators: - regex = '[^\\\\]' + sep - match = re.search(regex, string) - if match: - found[match.start() + 1] = sep + matches = re.finditer(sep, string) + for match in matches: + start, end = match.span() + inside_escape = False + for estart, eend in found_escapes: + if start >= estart and end <= eend: + inside_escape = True + break + if not inside_escape: + found[start] = sep if not found: #noinspection PyExceptionInherit
diff --git a/tests/tests.py b/tests/tests.py index 3302672..ea77d6a 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -76,6 +76,13 @@ class TestItemParsing(BaseTest): }) self.assertIn('bar@baz', files) + def test_escape_longsep(self): + headers, data, files = cli.parse_items([ + self.kv('bob\\:==foo'), + ]) + self.assertDictEqual(data, { + 'bob:=': 'foo', + }) def test_valid_items(self): headers, data, files = cli.parse_items([
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 rootdir: /home/user/BugsInPy/temp/projects/httpie plugins: httpbin-1.0.0 collected 1 item tests/tests.py F [100%] =================================== FAILURES =================================== _____________________ TestItemParsing.test_escape_longsep ______________________ self = <tests.TestItemParsing testMethod=test_escape_longsep> def test_escape_longsep(self): headers, data, files = cli.parse_items([ self.kv('bob\\:==foo'), ]) self.assertDictEqual(data, { > 'bob:=': 'foo', }) E AssertionError: {'bob:': '=foo'} != {'bob:=': 'foo'} E - {'bob:': '=foo'} E ? - E E + {'bob:=': 'foo'} E ? + tests/tests.py:84: AssertionError =========================== short test summary info ============================ FAILED tests/tests.py::TestItemParsing::test_escape_longsep - AssertionError:... ============================== 1 failed in 0.21s ===============================
pytest tests/tests.py::TestItemParsing::test_escape_longsep
16df8848e81eefac830f407e4b985f42b52970da
tests/tests.py
jakubroztocil__httpie-1
jakubroztocil/httpie
diff --git a/httpie/downloads.py b/httpie/downloads.py index b49e335..972151e 100644 --- a/httpie/downloads.py +++ b/httpie/downloads.py @@ -7,6 +7,7 @@ from __future__ import division import os import re import sys +import errno import mimetypes import threading from time import sleep, time @@ -135,12 +136,43 @@ def filename_from_url(url, content_type): return fn +def trim_filename(filename, max_len): + if len(filename) > max_len: + trim_by = len(filename) - max_len + name, ext = os.path.splitext(filename) + if trim_by >= len(name): + filename = filename[:-trim_by] + else: + filename = name[:-trim_by] + ext + return filename + + +def get_filename_max_length(directory): + try: + max_len = os.pathconf(directory, 'PC_NAME_MAX') + except OSError as e: + if e.errno == errno.EINVAL: + max_len = 255 + else: + raise + return max_len + + +def trim_filename_if_needed(filename, directory='.', extra=0): + max_len = get_filename_max_length(directory) - extra + if len(filename) > max_len: + filename = trim_filename(filename, max_len) + return filename + + def get_unique_filename(filename, exists=os.path.exists): attempt = 0 while True: suffix = '-' + str(attempt) if attempt > 0 else '' - if not exists(filename + suffix): - return filename + suffix + try_filename = trim_filename_if_needed(filename, extra=len(suffix)) + try_filename += suffix + if not exists(try_filename): + return try_filename attempt += 1
diff --git a/tests/test_downloads.py b/tests/test_downloads.py index 2d973c3..e09bdde 100644 --- a/tests/test_downloads.py +++ b/tests/test_downloads.py @@ -2,6 +2,7 @@ import os import time import pytest +import mock from requests.structures import CaseInsensitiveDict from httpie.compat import urlopen @@ -74,7 +75,31 @@ class TestDownloadUtils: content_type='x-foo/bar' ) - def test_unique_filename(self): + @pytest.mark.parametrize( + 'orig_name, unique_on_attempt, expected', + [ + # Simple + ('foo.bar', 0, 'foo.bar'), + ('foo.bar', 1, 'foo.bar-1'), + ('foo.bar', 10, 'foo.bar-10'), + # Trim + ('A' * 20, 0, 'A' * 10), + ('A' * 20, 1, 'A' * 8 + '-1'), + ('A' * 20, 10, 'A' * 7 + '-10'), + # Trim before ext + ('A' * 20 + '.txt', 0, 'A' * 6 + '.txt'), + ('A' * 20 + '.txt', 1, 'A' * 4 + '.txt-1'), + # Trim at the end + ('foo.' + 'A' * 20, 0, 'foo.' + 'A' * 6), + ('foo.' + 'A' * 20, 1, 'foo.' + 'A' * 4 + '-1'), + ('foo.' + 'A' * 20, 10, 'foo.' + 'A' * 3 + '-10'), + ] + ) + @mock.patch('httpie.downloads.get_filename_max_length') + def test_unique_filename(self, get_filename_max_length, + orig_name, unique_on_attempt, + expected): + def attempts(unique_on_attempt=0): # noinspection PyUnresolvedReferences,PyUnusedLocal def exists(filename): @@ -86,9 +111,10 @@ class TestDownloadUtils: exists.attempt = 0 return exists - assert 'foo.bar' == get_unique_filename('foo.bar', attempts(0)) - assert 'foo.bar-1' == get_unique_filename('foo.bar', attempts(1)) - assert 'foo.bar-10' == get_unique_filename('foo.bar', attempts(10)) + get_filename_max_length.return_value = 10 + + actual = get_unique_filename(orig_name, attempts(unique_on_attempt)) + assert expected == actual class TestDownloads:
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-3.2.1, py-1.8.1, pluggy-0.4.0 rootdir: /home/user/BugsInPy/temp/projects/httpie, inifile: pytest.ini plugins: httpbin-1.0.0 collected 11 items tests/test_downloads.py FFFFFFFFFFF =================================== FAILURES =================================== __________ TestDownloadUtils.test_unique_filename[foo.bar-0-foo.bar] ___________ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba5257e48>,) keywargs = {'expected': 'foo.bar', 'orig_name': 'foo.bar', 'unique_on_attempt': 0} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _________ TestDownloadUtils.test_unique_filename[foo.bar-1-foo.bar-1] __________ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2d7dba8>,) keywargs = {'expected': 'foo.bar-1', 'orig_name': 'foo.bar', 'unique_on_attempt': 1} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError ________ TestDownloadUtils.test_unique_filename[foo.bar-10-foo.bar-10] _________ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2e8c080>,) keywargs = {'expected': 'foo.bar-10', 'orig_name': 'foo.bar', 'unique_on_attempt': 10} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError __ TestDownloadUtils.test_unique_filename[AAAAAAAAAAAAAAAAAAAA-0-AAAAAAAAAA] ___ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2c69f98>,) keywargs = {'expected': 'AAAAAAAAAA', 'orig_name': 'AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 0} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError __ TestDownloadUtils.test_unique_filename[AAAAAAAAAAAAAAAAAAAA-1-AAAAAAAA-1] ___ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2ae1828>,) keywargs = {'expected': 'AAAAAAAA-1', 'orig_name': 'AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 1} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError __ TestDownloadUtils.test_unique_filename[AAAAAAAAAAAAAAAAAAAA-10-AAAAAAA-10] __ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2da8d30>,) keywargs = {'expected': 'AAAAAAA-10', 'orig_name': 'AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 10} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _ TestDownloadUtils.test_unique_filename[AAAAAAAAAAAAAAAAAAAA.txt-0-AAAAAA.txt] _ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2b2b630>,) keywargs = {'expected': 'AAAAAA.txt', 'orig_name': 'AAAAAAAAAAAAAAAAAAAA.txt', 'unique_on_attempt': 0} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _ TestDownloadUtils.test_unique_filename[AAAAAAAAAAAAAAAAAAAA.txt-1-AAAA.txt-1] _ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2da8898>,) keywargs = {'expected': 'AAAA.txt-1', 'orig_name': 'AAAAAAAAAAAAAAAAAAAA.txt', 'unique_on_attempt': 1} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _ TestDownloadUtils.test_unique_filename[foo.AAAAAAAAAAAAAAAAAAAA-0-foo.AAAAAA] _ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba27ff080>,) keywargs = {'expected': 'foo.AAAAAA', 'orig_name': 'foo.AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 0} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _ TestDownloadUtils.test_unique_filename[foo.AAAAAAAAAAAAAAAAAAAA-1-foo.AAAA-1] _ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2b3e828>,) keywargs = {'expected': 'foo.AAAA-1', 'orig_name': 'foo.AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 1} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError _ TestDownloadUtils.test_unique_filename[foo.AAAAAAAAAAAAAAAAAAAA-10-foo.AAA-10] _ args = (<test_downloads.TestDownloadUtils object at 0x7f1ba2818518>,) keywargs = {'expected': 'foo.AAA-10', 'orig_name': 'foo.AAAAAAAAAAAAAAAAAAAA', 'unique_on_attempt': 10} @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, > keywargs) as (newargs, newkeywargs): /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/contextlib.py:112: in __enter__ return next(self.gen) /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1334: in decoration_helper arg = patching.__enter__() /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1437: in __enter__ original, local = self.get_original() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <mock.mock._patch object at 0x7f1ba2fb2390> 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 'httpie.downloads' from '/opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/httpie-1.0.0.dev0-py3.7.egg/httpie/downloads.py'> does not have the attribute 'get_filename_max_length' /opt/conda/envs/f2ed64849367e3ce98d2d71a61cf95ea/lib/python3.7/site-packages/mock/mock.py:1411: AttributeError ========================== 11 failed in 5.35 seconds ===========================
pytest tests/test_downloads.py::TestDownloadUtils::test_unique_filename
001bda19450ad85c91345eea3cfa3991e1d492ba
tests/test_downloads.py
keras-team__keras-19
keras-team/keras
diff --git a/keras/backend/cntk_backend.py b/keras/backend/cntk_backend.py index 59430400..4c436f6d 100644 --- a/keras/backend/cntk_backend.py +++ b/keras/backend/cntk_backend.py @@ -1439,7 +1439,7 @@ def rnn(step_function, inputs, initial_states, for o, p in zip(new_states, place_holders): n_s.append(o.replace_placeholders({p: o.output})) if len(n_s) > 0: - new_output = n_s[0] + new_output = n_s[-1] return new_output, n_s final_output, final_states = _recurrence(rnn_inputs, states, mask) diff --git a/keras/layers/recurrent.py b/keras/layers/recurrent.py index 30859a93..c82e6a32 100644 --- a/keras/layers/recurrent.py +++ b/keras/layers/recurrent.py @@ -54,36 +54,56 @@ class StackedRNNCells(Layer): '`state_size` attribute. ' 'received cells:', cells) self.cells = cells + # reverse_state_order determines whether the state size will be in a + # reverse order of the cells' state. User might want to set this to True + # to keep the existing behavior. This is only useful when use + # `RNN(return_state=True)` since the state will be returned as the same + # order of state_size. + self.reverse_state_order = kwargs.pop('reverse_state_order', False) + if self.reverse_state_order: + warnings.warn('`reverse_state_order=True` in `StackedRNNCells` ' + 'will soon be deprecated. Please update the code to ' + 'work with the natural order of states if you ' + 'reply on the RNN states, ' + 'eg `RNN(return_state=True)`.') super(StackedRNNCells, self).__init__(**kwargs) @property def state_size(self): - # States are a flat list - # in reverse order of the cell stack. - # This allows to preserve the requirement - # `stack.state_size[0] == output_dim`. - # e.g. states of a 2-layer LSTM would be - # `[h2, c2, h1, c1]` + # States are a flat list of the individual cell state size. + # e.g. states of a 2-layer LSTM would be `[h1, c1, h2, c2]`. # (assuming one LSTM has states [h, c]) + # In the case of reverse_state_order=True, the state_size will be + # `[h2, c2, h1, c1]`. state_size = [] - for cell in self.cells[::-1]: + for cell in self.cells[::-1] if self.reverse_state_order else self.cells: if hasattr(cell.state_size, '__len__'): state_size += list(cell.state_size) else: state_size.append(cell.state_size) return tuple(state_size) + @property + def output_size(self): + if getattr(self.cells[-1], 'output_size', None) is not None: + return self.cells[-1].output_size + if hasattr(self.cells[-1].state_size, '__len__'): + return self.cells[-1].state_size[0] + else: + return self.cells[-1].state_size + def call(self, inputs, states, constants=None, **kwargs): # Recover per-cell states. nested_states = [] - for cell in self.cells[::-1]: + for cell in self.cells[::-1] if self.reverse_state_order else self.cells: if hasattr(cell.state_size, '__len__'): nested_states.append(states[:len(cell.state_size)]) states = states[len(cell.state_size):] else: nested_states.append([states[0]]) states = states[1:] - nested_states = nested_states[::-1] + if self.reverse_state_order: + nested_states = nested_states[::-1] # Call the cells in order and store the returned states. new_nested_states = [] @@ -98,10 +118,12 @@ class StackedRNNCells(Layer): # Format the new states as a flat list # in reverse cell order. - states = [] - for cell_states in new_nested_states[::-1]: - states += cell_states - return inputs, states + new_states = [] + if self.reverse_state_order: + new_nested_states = new_nested_states[::-1] + for cell_states in new_nested_states: + new_states += cell_states + return inputs, new_states def build(self, input_shape): if isinstance(input_shape, list): @@ -113,7 +135,9 @@ class StackedRNNCells(Layer): cell.build([input_shape] + constants_shape) else: cell.build(input_shape) - if hasattr(cell.state_size, '__len__'): + if getattr(cell, 'output_size', None) is not None: + output_dim = cell.output_size + elif hasattr(cell.state_size, '__len__'): output_dim = cell.state_size[0] else: output_dim = cell.state_size @@ -223,9 +247,12 @@ class RNN(Layer): the size of the recurrent state (which should be the same as the size of the cell output). This can also be a list/tuple of integers - (one size per state). In this case, the first entry - (`state_size[0]`) should be the same as - the size of the cell output. + (one size per state). + - a `output_size` attribute. This can be a single integer or a + TensorShape, which represent the shape of the output. For + backward compatible reason, if this attribute is not available + for the cell, the value will be inferred by the first element + of the `state_size`. It is also possible for `cell` to be a list of RNN cell instances, in which cases the cells get stacked on after the other in the RNN, implementing an efficient stacked RNN. @@ -414,7 +441,11 @@ class RNN(Layer): state_size = self.cell.state_size else: state_size = [self.cell.state_size] - output_dim = state_size[0] + + if getattr(self.cell, 'output_size', None) is not None: + output_dim = self.cell.output_size + else: + output_dim = state_size[0] if self.return_sequences: output_shape = (input_shape[0], input_shape[1], output_dim) @@ -827,6 +858,7 @@ class SimpleRNNCell(Layer): self.dropout = min(1., max(0., dropout)) self.recurrent_dropout = min(1., max(0., recurrent_dropout)) self.state_size = self.units + self.output_size = self.units self._dropout_mask = None self._recurrent_dropout_mask = None @@ -1220,6 +1252,7 @@ class GRUCell(Layer): self.implementation = implementation self.reset_after = reset_after self.state_size = self.units + self.output_size = self.units self._dropout_mask = None self._recurrent_dropout_mask = None @@ -1795,6 +1828,7 @@ class LSTMCell(Layer): self.recurrent_dropout = min(1., max(0., recurrent_dropout)) self.implementation = implementation self.state_size = (self.units, self.units) + self.output_size = self.units self._dropout_mask = None self._recurrent_dropout_mask = None
diff --git a/tests/keras/layers/recurrent_test.py b/tests/keras/layers/recurrent_test.py index 8c5814bd8..c0497236c 100644 --- a/tests/keras/layers/recurrent_test.py +++ b/tests/keras/layers/recurrent_test.py @@ -499,7 +499,7 @@ def test_minimal_rnn_cell_non_layer_multiple_states(): MinimalRNNCell(16, 8), MinimalRNNCell(32, 16)] layer = recurrent.RNN(cells) - assert layer.cell.state_size == (32, 32, 16, 16, 8, 8) + assert layer.cell.state_size == (8, 8, 16, 16, 32, 32) y = layer(x) model = keras.models.Model(x, y) model.compile(optimizer='rmsprop', loss='mse') @@ -678,6 +678,19 @@ def test_stacked_rnn_compute_output_shape(): recurrent.LSTMCell(6)] layer = recurrent.RNN(cells, return_state=True, return_sequences=True) output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) + expected_output_shape = [(None, timesteps, 6), + (None, 3), + (None, 3), + (None, 6), + (None, 6)] + assert output_shape == expected_output_shape + + # Test reverse_state_order = True for stacked cell. + stacked_cell = recurrent.StackedRNNCells( + cells, reverse_state_order=True) + layer = recurrent.RNN( + stacked_cell, return_state=True, return_sequences=True) + output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) expected_output_shape = [(None, timesteps, 6), (None, 6), (None, 6), @@ -907,5 +920,48 @@ def test_rnn_cell_identity_initializer(layer_class): np.concatenate([np.identity(units)] * num_kernels, axis=1)) +@keras_test [email protected](K.backend() == 'cntk', reason='Not supported.') +def test_inconsistent_output_state_size(): + + class PlusOneRNNCell(keras.layers.Layer): + """Add one to the input and state. + + This cell is used for testing state_size and output_size.""" + + def __init__(self, num_unit, **kwargs): + self.state_size = num_unit + super(PlusOneRNNCell, self).__init__(**kwargs) + + def build(self, input_shape): + self.output_size = input_shape[-1] + + def call(self, inputs, states): + return inputs + 1, [states[0] + 1] + + batch = 32 + time_step = 4 + state_size = 5 + input_size = 6 + cell = PlusOneRNNCell(state_size) + x = keras.Input((None, input_size)) + layer = recurrent.RNN(cell) + y = layer(x) + + assert cell.state_size == state_size + init_state = layer.get_initial_state(x) + assert len(init_state) == 1 + if K.backend() != 'theano': + # theano does not support static shape inference. + assert K.int_shape(init_state[0]) == (None, state_size) + + model = keras.models.Model(x, y) + model.compile(optimizer='rmsprop', loss='mse') + model.train_on_batch( + np.zeros((batch, time_step, input_size)), + np.zeros((batch, input_size))) + assert model.output_shape == (None, input_size) + + if __name__ == '__main__': pytest.main([__file__])
0 ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size [gw0] [100%] FAILED tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size =================================== FAILURES =================================== _____________________ test_inconsistent_output_state_size ______________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python @keras_test @pytest.mark.skipif(K.backend() == 'cntk', reason='Not supported.') def test_inconsistent_output_state_size(): class PlusOneRNNCell(keras.layers.Layer): """Add one to the input and state. This cell is used for testing state_size and output_size.""" def __init__(self, num_unit, **kwargs): self.state_size = num_unit super(PlusOneRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.output_size = input_shape[-1] def call(self, inputs, states): return inputs + 1, [states[0] + 1] batch = 32 time_step = 4 state_size = 5 input_size = 6 cell = PlusOneRNNCell(state_size) x = keras.Input((None, input_size)) layer = recurrent.RNN(cell) y = layer(x) assert cell.state_size == state_size init_state = layer.get_initial_state(x) assert len(init_state) == 1 if K.backend() != 'theano': # theano does not support static shape inference. assert K.int_shape(init_state[0]) == (None, state_size) model = keras.models.Model(x, y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch( np.zeros((batch, time_step, input_size)), > np.zeros((batch, input_size))) tests/keras/layers/recurrent_test.py:962: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/engine/training.py:1217: in train_on_batch class_weight=class_weight) keras/engine/training.py:795: in _standardize_user_data exception_prefix='target') _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ data = [array([[0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [0., 0., 0...., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.]])] names = ['rnn_1'], shapes = [(None, 5)], check_batch_axis = False exception_prefix = 'target' def standardize_input_data(data, names, shapes=None, check_batch_axis=True, exception_prefix=''): """Normalizes inputs and targets provided by users. Users may pass data as a list of arrays, dictionary of arrays, or as a single array. We normalize this to an ordered list of arrays (same order as `names`), while checking that the provided arrays have shapes that match the network's expectations. # Arguments data: User-provided input data (polymorphic). names: List of expected array names. shapes: Optional list of expected array shapes. check_batch_axis: Boolean; whether to check that the batch axis of the arrays matches the expected value found in `shapes`. exception_prefix: String prefix used for exception formatting. # Returns List of standardized input arrays (one array per model input). # Raises ValueError: in case of improperly formatted user-provided data. """ if not names: if data is not None and hasattr(data, '__len__') and len(data): raise ValueError('Error when checking model ' + exception_prefix + ': ' 'expected no data, but got:', data) return [] if data is None: return [None for _ in range(len(names))] if isinstance(data, dict): try: data = [ data[x].values if data[x].__class__.__name__ == 'DataFrame' else data[x] for x in names ] except KeyError as e: raise ValueError('No data provided for "' + e.args[0] + '". Need data ' 'for each key in: ' + str(names)) elif isinstance(data, list): if isinstance(data[0], list): data = [np.asarray(d) for d in data] elif len(names) == 1 and isinstance(data[0], (float, int)): data = [np.asarray(data)] else: data = [ x.values if x.__class__.__name__ == 'DataFrame' else x for x in data ] else: data = data.values if data.__class__.__name__ == 'DataFrame' else data data = [data] data = [standardize_single_array(x) for x in data] if len(data) != len(names): if data and hasattr(data[0], 'shape'): raise ValueError( 'Error when checking model ' + exception_prefix + ': the list of Numpy arrays that you are passing to ' 'your model is not the size the model expected. ' 'Expected to see ' + str(len(names)) + ' array(s), ' 'but instead got the following list of ' + str(len(data)) + ' arrays: ' + str(data)[:200] + '...') elif len(names) > 1: raise ValueError( 'Error when checking model ' + exception_prefix + ': you are passing a list as input to your model, ' 'but the model expects a list of ' + str(len(names)) + ' Numpy arrays instead. ' 'The list you passed was: ' + str(data)[:200]) elif len(data) == 1 and not hasattr(data[0], 'shape'): raise TypeError('Error when checking model ' + exception_prefix + ': data should be a Numpy array, or list/dict of ' 'Numpy arrays. Found: ' + str(data)[:200] + '...') elif len(names) == 1: data = [np.asarray(data)] # Check shapes compatibility. if shapes: for i in range(len(names)): if shapes[i] is not None and not K.is_tensor(data[i]): data_shape = data[i].shape shape = shapes[i] if data[i].ndim != len(shape): raise ValueError( 'Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have ' + str(len(shape)) + ' dimensions, but got array ' 'with shape ' + str(data_shape)) if not check_batch_axis: data_shape = data_shape[1:] shape = shape[1:] for dim, ref_dim in zip(data_shape, shape): if ref_dim != dim and ref_dim: raise ValueError( 'Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have shape ' + str(shape) + ' but got array with shape ' + > str(data_shape)) E ValueError: Error when checking target: expected rnn_1 to have shape (5,) but got array with shape (6,) keras/engine/training_utils.py:138: ValueError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:782: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:782: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. =============================== warnings summary =============================== /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.11s call tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size ======================== 1 failed, 61 warnings in 8.36s ======================== RUN EVERY COMMAND 1 pytest tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states [gw0] [100%] FAILED tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states =================================== FAILURES =================================== _______________ test_minimal_rnn_cell_non_layer_multiple_states ________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python @keras_test def test_minimal_rnn_cell_non_layer_multiple_states(): class MinimalRNNCell(object): def __init__(self, units, input_dim): self.units = units self.state_size = (units, units) self.kernel = keras.backend.variable( np.random.random((input_dim, units))) def call(self, inputs, states): prev_output_1 = states[0] prev_output_2 = states[1] output = keras.backend.dot(inputs, self.kernel) output += prev_output_1 output -= prev_output_2 return output, [output * 2, output * 3] # Basic test case. cell = MinimalRNNCell(32, 5) x = keras.Input((None, 5)) layer = recurrent.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [MinimalRNNCell(8, 5), MinimalRNNCell(16, 8), MinimalRNNCell(32, 16)] layer = recurrent.RNN(cells) > assert layer.cell.state_size == (8, 8, 16, 16, 32, 32) E assert (32, 32, 16, 16, 8, 8) == (8, 8, 16, 16, 32, 32) E At index 0 diff: 32 != 8 E Full diff: E - (8, 8, 16, 16, 32, 32) E + (32, 32, 16, 16, 8, 8) tests/keras/layers/recurrent_test.py:502: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:782: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2702: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. 2023-07-15 05:16:21.525737: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 05:16:21.530184: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 05:16:21.530341: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x556bf3df9ff0 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 05:16:21.530353: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 05:16:21.531385: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 05:16:21.531400: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 05:16:21.531414: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (8cd2fa7be075): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:782: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2702: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. =============================== warnings summary =============================== /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.26s call tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states ======================== 1 failed, 65 warnings in 9.90s ========================
pytest tests/keras/layers/recurrent_test.py::test_inconsistent_output_state_size pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states
f9210387088fe91b5bc8999cf0cb41a0fe9eacf6
tests/keras/layers/recurrent_test.py
keras-team__keras-4
keras-team/keras
diff --git a/keras/optimizers.py b/keras/optimizers.py index 0dade2fd..89fe2967 100644 --- a/keras/optimizers.py +++ b/keras/optimizers.py @@ -703,7 +703,7 @@ class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): - grads = self.optimizer.compute_gradients(loss, params) + grads = self.optimizer.compute_gradients(loss, var_list=params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=self.iterations)
diff --git a/tests/keras/optimizers_test.py b/tests/keras/optimizers_test.py index 312033356..c118f4571 100644 --- a/tests/keras/optimizers_test.py +++ b/tests/keras/optimizers_test.py @@ -148,5 +148,30 @@ def test_tfoptimizer(): optimizer.from_config(None) [email protected]((K.backend() != 'tensorflow'), + reason='Requires TensorFlow backend') +def test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer(): + from keras import constraints + from tensorflow import train + + class MyTfOptimizer(train.Optimizer): + wrapping_optimizer = train.AdamOptimizer() + + def compute_gradients(self, loss, **kwargs): + return super(MyTfOptimizer, self).compute_gradients(loss, **kwargs) + + def apply_gradients(self, grads_and_vars, **kwargs): + return self.wrapping_optimizer.apply_gradients(grads_and_vars, + **kwargs) + my_tf_optimizer = MyTfOptimizer(use_locking=False, name='MyTfOptimizer') + optimizer = optimizers.TFOptimizer(my_tf_optimizer) + model = Sequential() + model.add(Dense(num_classes, input_shape=(3,), + kernel_constraint=constraints.MaxNorm(1))) + model.compile(loss='mean_squared_error', optimizer=optimizer) + model.fit(np.random.random((5, 3)), np.random.random((5, num_classes)), + epochs=1, batch_size=5, verbose=0) + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer [gw0] [100%] FAILED tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer =================================== FAILURES =================================== __ test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer ___ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python @pytest.mark.skipif((K.backend() != 'tensorflow'), reason='Requires TensorFlow backend') def test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer(): from keras import constraints from tensorflow import train class MyTfOptimizer(train.Optimizer): wrapping_optimizer = train.AdamOptimizer() def compute_gradients(self, loss, **kwargs): return super(MyTfOptimizer, self).compute_gradients(loss, **kwargs) def apply_gradients(self, grads_and_vars, **kwargs): return self.wrapping_optimizer.apply_gradients(grads_and_vars, **kwargs) my_tf_optimizer = MyTfOptimizer(use_locking=False, name='MyTfOptimizer') optimizer = optimizers.TFOptimizer(my_tf_optimizer) model = Sequential() model.add(Dense(num_classes, input_shape=(3,), kernel_constraint=constraints.MaxNorm(1))) model.compile(loss='mean_squared_error', optimizer=optimizer) model.fit(np.random.random((5, 3)), np.random.random((5, num_classes)), > epochs=1, batch_size=5, verbose=0) tests/keras/optimizers_test.py:173: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/engine/training.py:1026: in fit self._make_train_function() keras/engine/training.py:509: in _make_train_function loss=self.total_loss) keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <keras.optimizers.TFOptimizer object at 0x7f9bf6af6e10> loss = <tf.Tensor 'loss/mul:0' shape=() dtype=float32> params = [<tf.Variable 'dense_1/kernel:0' shape=(3, 2) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(2,) dtype=float32_ref>] @interfaces.legacy_get_updates_support def get_updates(self, loss, params): > grads = self.optimizer.compute_gradients(loss, params) E TypeError: compute_gradients() takes 2 positional arguments but 3 were given keras/optimizers.py:706: TypeError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/tests/keras/optimizers_test.py:157: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/tests/keras/optimizers_test.py:158: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4377: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/tests/keras/optimizers_test.py:157: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/tests/keras/optimizers_test.py:158: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4377: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.19s call tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer 0.01s teardown tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer ======================== 1 failed, 2 warnings in 18.49s ======================== Using TensorFlow backend.
pytest tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer
b0bfd5201da2bfced84028bcc5bda05bdfd75af7
tests/keras/optimizers_test.py
keras-team__keras-13
keras-team/keras
diff --git a/keras/engine/training_generator.py b/keras/engine/training_generator.py index 5c5697c5..3c480f22 100644 --- a/keras/engine/training_generator.py +++ b/keras/engine/training_generator.py @@ -124,7 +124,8 @@ def fit_generator(model, elif val_gen: val_data = validation_data if isinstance(val_data, Sequence): - val_enqueuer_gen = iter_sequence_infinite(generator) + val_enqueuer_gen = iter_sequence_infinite(val_data) + validation_steps = validation_steps or len(val_data) else: val_enqueuer_gen = val_data else:
diff --git a/tests/keras/engine/test_training.py b/tests/keras/engine/test_training.py index 9f767649c..bc0d415aa 100644 --- a/tests/keras/engine/test_training.py +++ b/tests/keras/engine/test_training.py @@ -468,6 +468,19 @@ def test_model_methods(): assert trained_batches == list(range(12)) * 5 assert len(val_seq.logs) == 12 * 5 + # test for workers = 0 + trained_epochs = [] + trained_batches = [] + val_seq = RandomSequence(4) + out = model.fit_generator(generator=RandomSequence(3), + epochs=5, + validation_data=val_seq, + callbacks=[tracker_cb], + workers=0) + assert trained_epochs == [0, 1, 2, 3, 4] + assert trained_batches == list(range(12)) * 5 + assert len(val_seq.logs) == 12 * 5 + # fit_generator will throw an exception # if steps is unspecified for regular generator with pytest.raises(ValueError):
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/engine/test_training.py::test_model_methods [gw0] [100%] FAILED tests/keras/engine/test_training.py::test_model_methods =================================== FAILURES =================================== ______________________________ test_model_methods ______________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/bin/python def test_model_methods(): a = Input(shape=(3,), name='input_a') b = Input(shape=(3,), name='input_b') a_2 = Dense(4, name='dense_1')(a) dp = Dropout(0.5, name='dropout') b_2 = dp(b) model = Model([a, b], [a_2, b_2]) optimizer = 'rmsprop' loss = 'mse' loss_weights = [1., 0.5] input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) # training/testing doesn't work before compiling. with pytest.raises(RuntimeError): model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) # test train_on_batch out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) out = model.train_on_batch({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np]) out = model.train_on_batch({'input_a': input_a_np, 'input_b': input_b_np}, {'dense_1': output_a_np, 'dropout': output_b_np}) # test fit out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], epochs=1, batch_size=4) out = model.fit({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np], epochs=1, batch_size=4) out = model.fit({'input_a': input_a_np, 'input_b': input_b_np}, {'dense_1': output_a_np, 'dropout': output_b_np}, epochs=1, batch_size=4) # test validation_split out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], epochs=1, batch_size=4, validation_split=0.5) out = model.fit({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np], epochs=1, batch_size=4, validation_split=0.5) # test validation data out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], epochs=1, batch_size=4, validation_data=([input_a_np, input_b_np], [output_a_np, output_b_np])) out = model.fit({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np], epochs=1, batch_size=4, validation_split=0.5, validation_data=({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np])) out = model.fit({'input_a': input_a_np, 'input_b': input_b_np}, {'dense_1': output_a_np, 'dropout': output_b_np}, epochs=1, batch_size=4, validation_split=0.5, validation_data=( {'input_a': input_a_np, 'input_b': input_b_np}, {'dense_1': output_a_np, 'dropout': output_b_np})) # test_on_batch out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) out = model.test_on_batch({'input_a': input_a_np, 'input_b': input_b_np}, [output_a_np, output_b_np]) out = model.test_on_batch({'input_a': input_a_np, 'input_b': input_b_np}, {'dense_1': output_a_np, 'dropout': output_b_np}) # predict_on_batch out = model.predict_on_batch([input_a_np, input_b_np]) out = model.predict_on_batch({'input_a': input_a_np, 'input_b': input_b_np}) # predict, evaluate input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) out = model.evaluate([input_a_np, input_b_np], [output_a_np, output_b_np], batch_size=4) out = model.predict([input_a_np, input_b_np], batch_size=4) # with sample_weight input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) sample_weight = [None, np.random.random((10,))] out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=sample_weight) out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=sample_weight) # test accuracy metric model.compile(optimizer, loss, metrics=['acc'], sample_weight_mode=None) out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 5 out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 5 # this should also work model.compile(optimizer, loss, metrics={'dense_1': 'acc'}, sample_weight_mode=None) out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 4 out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 4 # and this as well model.compile(optimizer, loss, metrics={'dense_1': ['acc']}, sample_weight_mode=None) out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 4 out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == 4 # test starting from non-zero initial epoch trained_epochs = [] trained_batches = [] # define tracer callback def on_epoch_begin(epoch, logs): trained_epochs.append(epoch) def on_batch_begin(batch, logs): trained_batches.append(batch) tracker_cb = LambdaCallback(on_epoch_begin=on_epoch_begin, on_batch_begin=on_batch_begin) out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], epochs=5, batch_size=4, initial_epoch=2, callbacks=[tracker_cb]) assert trained_epochs == [2, 3, 4] # test starting from non-zero initial epoch for generator too trained_epochs = [] @threadsafe_generator def gen_data(batch_sz): while True: yield ([np.random.random((batch_sz, 3)), np.random.random((batch_sz, 3))], [np.random.random((batch_sz, 4)), np.random.random((batch_sz, 3))]) out = model.fit_generator(gen_data(4), steps_per_epoch=3, epochs=5, initial_epoch=2, callbacks=[tracker_cb]) assert trained_epochs == [2, 3, 4] # test with a custom metric function def mse(y_true, y_pred): return K.mean(K.pow(y_true - y_pred, 2)) model.compile(optimizer, loss, metrics=[mse], sample_weight_mode=None) out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) out_len = 1 + 2 * (1 + 1) # total loss + 2 outputs * (loss + metric) assert len(out) == out_len out = model.test_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) assert len(out) == out_len input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], batch_size=4, epochs=1) out = model.evaluate([input_a_np, input_b_np], [output_a_np, output_b_np], batch_size=4) out = model.predict([input_a_np, input_b_np], batch_size=4) # enable verbose for evaluate_generator out = model.evaluate_generator(gen_data(4), steps=3, verbose=1) # empty batch with pytest.raises(ValueError): @threadsafe_generator def gen_data(): while True: yield (np.asarray([]), np.asarray([])) out = model.evaluate_generator(gen_data(), steps=1) # x is not a list of numpy arrays. with pytest.raises(ValueError): out = model.predict([None]) # x does not match _feed_input_names. with pytest.raises(ValueError): out = model.predict([input_a_np, None, input_b_np]) with pytest.raises(ValueError): out = model.predict([None, input_a_np, input_b_np]) # all input/output/weight arrays should have the same number of samples. with pytest.raises(ValueError): out = model.train_on_batch([input_a_np, input_b_np[:2]], [output_a_np, output_b_np], sample_weight=sample_weight) with pytest.raises(ValueError): out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np[:2]], sample_weight=sample_weight) with pytest.raises(ValueError): out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=[sample_weight[1], sample_weight[1][:2]]) # `sample_weight` is neither a dict nor a list. with pytest.raises(TypeError): out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=tuple(sample_weight)) # `validation_data` is neither a tuple nor a triple. with pytest.raises(ValueError): out = model.fit([input_a_np, input_b_np], [output_a_np, output_b_np], epochs=1, batch_size=4, validation_data=([input_a_np, input_b_np],)) # `loss` does not match outputs. with pytest.raises(ValueError): model.compile(optimizer, loss=['mse', 'mae', 'mape']) # `loss_weights` does not match output_names. with pytest.raises(ValueError): model.compile(optimizer, loss='mse', loss_weights={'lstm': 0.5}) # `loss_weights` does not match outputs. with pytest.raises(ValueError): model.compile(optimizer, loss='mse', loss_weights=[0.5]) # `loss_weights` is invalid type. with pytest.raises(TypeError): model.compile(optimizer, loss='mse', loss_weights=(0.5, 0.5)) # `sample_weight_mode` does not match output_names. with pytest.raises(ValueError): model.compile(optimizer, loss='mse', sample_weight_mode={'lstm': 'temporal'}) # `sample_weight_mode` does not match output_names. with pytest.raises(ValueError): model.compile(optimizer, loss='mse', sample_weight_mode=['temporal']) # `sample_weight_mode` matches output_names partially. with pytest.raises(ValueError): model.compile(optimizer, loss='mse', sample_weight_mode={'dense_1': 'temporal'}) # `loss` does not exist. with pytest.raises(ValueError): model.compile(optimizer, loss=[]) model.compile(optimizer, loss=['mse', 'mae']) model.compile(optimizer, loss='mse', loss_weights={'dense_1': 0.2, 'dropout': 0.8}) model.compile(optimizer, loss='mse', loss_weights=[0.2, 0.8]) # the rank of weight arrays should be 1. with pytest.raises(ValueError): out = model.train_on_batch( [input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=[None, np.random.random((10, 20, 30))]) model.compile(optimizer, loss='mse', sample_weight_mode={'dense_1': None, 'dropout': 'temporal'}) model.compile(optimizer, loss='mse', sample_weight_mode=[None, 'temporal']) # the rank of output arrays should be at least 3D. with pytest.raises(ValueError): out = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], sample_weight=sample_weight) model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) trained_epochs = [] trained_batches = [] val_seq = RandomSequence(4) out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=3, epochs=5, initial_epoch=0, validation_data=val_seq, validation_steps=3, max_queue_size=1, callbacks=[tracker_cb]) assert trained_epochs == [0, 1, 2, 3, 4] assert trained_batches == list(range(3)) * 5 assert len(val_seq.logs) <= 4 * 5 # steps_per_epoch will be equal to len of sequence if it's unspecified trained_epochs = [] trained_batches = [] val_seq = RandomSequence(4) out = model.fit_generator(generator=RandomSequence(3), epochs=5, initial_epoch=0, validation_data=val_seq, callbacks=[tracker_cb]) assert trained_epochs == [0, 1, 2, 3, 4] assert trained_batches == list(range(12)) * 5 assert len(val_seq.logs) == 12 * 5 # test for workers = 0 trained_epochs = [] trained_batches = [] val_seq = RandomSequence(4) out = model.fit_generator(generator=RandomSequence(3), epochs=5, validation_data=val_seq, callbacks=[tracker_cb], > workers=0) tests/keras/engine/test_training.py:479: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) keras/engine/training.py:1418: in fit_generator initial_epoch=initial_epoch) keras/engine/training_generator.py:233: in fit_generator workers=0) keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) keras/engine/training.py:1472: in evaluate_generator verbose=verbose) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ model = <keras.engine.training.Model object at 0x7f0ca0844a90> generator = <generator object iter_sequence_infinite at 0x7f0ca0a76840> steps = None, max_queue_size = 10, workers = 0, use_multiprocessing = False verbose = 0 def evaluate_generator(model, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0): """See docstring for `Model.evaluate_generator`.""" model._make_test_function() if hasattr(model, 'metrics'): for m in model.stateful_metric_functions: m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(model.metrics_names) if str(name) in model.stateful_metric_names] else: stateful_metric_indices = [] steps_done = 0 wait_time = 0.01 outs_per_batch = [] batch_sizes = [] is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) else: > raise ValueError('`steps=None` is only valid for a generator' ' based on the `keras.utils.Sequence` class.' ' Please specify `steps` or use the' ' `keras.utils.Sequence` class.') E ValueError: `steps=None` is only valid for a generator based on the `keras.utils.Sequence` class. Please specify `steps` or use the `keras.utils.Sequence` class. keras/engine/training_generator.py:300: ValueError ----------------------------- Captured stdout call ----------------------------- Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 1.0782 - dense_1_loss: 0.8449 - dropout_loss: 0.4666 10/10 [==============================] - 0s 1ms/step - loss: 0.9060 - dense_1_loss: 0.6863 - dropout_loss: 0.4394 Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 0.6729 - dense_1_loss: 0.4543 - dropout_loss: 0.4372 10/10 [==============================] - 0s 385us/step - loss: 1.0240 - dense_1_loss: 0.6706 - dropout_loss: 0.7067 Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 1.0185 - dense_1_loss: 0.8247 - dropout_loss: 0.3876 10/10 [==============================] - 0s 2ms/step - loss: 0.9082 - dense_1_loss: 0.6577 - dropout_loss: 0.5011 Train on 5 samples, validate on 5 samples Epoch 1/1 4/5 [=======================>......] - ETA: 0s - loss: 0.7268 - dense_1_loss: 0.4431 - dropout_loss: 0.5674 5/5 [==============================] - 0s 15ms/step - loss: 0.7023 - dense_1_loss: 0.4487 - dropout_loss: 0.5073 - val_loss: 0.9505 - val_dense_1_loss: 0.8427 - val_dropout_loss: 0.2154 Train on 5 samples, validate on 5 samples Epoch 1/1 4/5 [=======================>......] - ETA: 0s - loss: 0.6208 - dense_1_loss: 0.4168 - dropout_loss: 0.4081 5/5 [==============================] - 0s 468us/step - loss: 0.6494 - dense_1_loss: 0.4439 - dropout_loss: 0.4110 - val_loss: 0.9438 - val_dense_1_loss: 0.8361 - val_dropout_loss: 0.2154 Train on 10 samples, validate on 10 samples Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 1.0281 - dense_1_loss: 0.7701 - dropout_loss: 0.5161 10/10 [==============================] - 0s 338us/step - loss: 0.9289 - dense_1_loss: 0.6353 - dropout_loss: 0.5873 - val_loss: 0.7194 - val_dense_1_loss: 0.6275 - val_dropout_loss: 0.1837 Train on 10 samples, validate on 10 samples Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 0.8974 - dense_1_loss: 0.7500 - dropout_loss: 0.2949 10/10 [==============================] - 0s 323us/step - loss: 0.7866 - dense_1_loss: 0.6250 - dropout_loss: 0.3232 - val_loss: 0.7094 - val_dense_1_loss: 0.6176 - val_dropout_loss: 0.1837 Train on 10 samples, validate on 10 samples Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 0.5788 - dense_1_loss: 0.3975 - dropout_loss: 0.3627 10/10 [==============================] - 0s 1ms/step - loss: 0.8464 - dense_1_loss: 0.6149 - dropout_loss: 0.4630 - val_loss: 0.6987 - val_dense_1_loss: 0.6068 - val_dropout_loss: 0.1837 4/10 [===========>..................] - ETA: 0s 10/10 [==============================] - 0s 1ms/step Epoch 3/5 4/10 [===========>..................] - ETA: 0s - loss: 1.5069 - dense_1_loss: 1.1515 - dropout_loss: 0.3555 - dense_1_acc: 0.0000e+00 10/10 [==============================] - 0s 201us/step - loss: 1.2259 - dense_1_loss: 0.7304 - dropout_loss: 0.4955 - dense_1_acc: 0.1000 Epoch 4/5 4/10 [===========>..................] - ETA: 0s - loss: 1.2554 - dense_1_loss: 0.6097 - dropout_loss: 0.6457 - dense_1_acc: 0.2500 10/10 [==============================] - 0s 167us/step - loss: 1.1998 - dense_1_loss: 0.7139 - dropout_loss: 0.4859 - dense_1_acc: 0.1000 Epoch 5/5 4/10 [===========>..................] - ETA: 0s - loss: 0.9116 - dense_1_loss: 0.5173 - dropout_loss: 0.3943 - dense_1_acc: 0.0000e+00 10/10 [==============================] - 0s 167us/step - loss: 1.2833 - dense_1_loss: 0.7010 - dropout_loss: 0.5824 - dense_1_acc: 0.1000 Epoch 3/5 1/3 [=========>....................] - ETA: 0s - loss: 0.8143 - dense_1_loss: 0.2503 - dropout_loss: 0.5640 - dense_1_acc: 0.0000e+00 3/3 [==============================] - 0s 7ms/step - loss: 1.3456 - dense_1_loss: 0.7326 - dropout_loss: 0.6130 - dense_1_acc: 0.1667 Epoch 4/5 1/3 [=========>....................] - ETA: 0s - loss: 1.0001 - dense_1_loss: 0.4140 - dropout_loss: 0.5861 - dense_1_acc: 0.2500 3/3 [==============================] - 0s 7ms/step - loss: 1.3001 - dense_1_loss: 0.6916 - dropout_loss: 0.6085 - dense_1_acc: 0.5000 Epoch 5/5 1/3 [=========>....................] - ETA: 0s - loss: 1.0902 - dense_1_loss: 0.5695 - dropout_loss: 0.5207 - dense_1_acc: 0.2500 3/3 [==============================] - 0s 843us/step - loss: 1.1416 - dense_1_loss: 0.5878 - dropout_loss: 0.5538 - dense_1_acc: 0.1667 Epoch 1/1 4/10 [===========>..................] - ETA: 0s - loss: 0.9214 - dense_1_loss: 0.4427 - dropout_loss: 0.4787 - dense_1_mse: 0.4427 - dropout_mse: 0.4787 10/10 [==============================] - 0s 1ms/step - loss: 1.0606 - dense_1_loss: 0.5339 - dropout_loss: 0.5267 - dense_1_mse: 0.5339 - dropout_mse: 0.5267 4/10 [===========>..................] - ETA: 0s 10/10 [==============================] - 0s 101us/step 1/3 [=========>....................] - ETA: 0s 3/3 [==============================] - 0s 5ms/step Epoch 1/5 1/3 [=========>....................] - ETA: 1s - loss: 1.0200 - dense_1_loss: 0.7932 - dropout_loss: 0.4535 3/3 [==============================] - 1s 267ms/step - loss: 0.9972 - dense_1_loss: 0.7650 - dropout_loss: 0.4644 - val_loss: 0.6696 - val_dense_1_loss: 0.5669 - val_dropout_loss: 0.2055 Epoch 2/5 1/3 [=========>....................] - ETA: 0s - loss: 1.1016 - dense_1_loss: 0.5297 - dropout_loss: 1.1437 3/3 [==============================] - 0s 1ms/step - loss: 0.8410 - dense_1_loss: 0.5286 - dropout_loss: 0.6249 - val_loss: 0.8324 - val_dense_1_loss: 0.7629 - val_dropout_loss: 0.1388 Epoch 3/5 1/3 [=========>....................] - ETA: 0s - loss: 0.4373 - dense_1_loss: 0.2112 - dropout_loss: 0.4521 3/3 [==============================] - 0s 7ms/step - loss: 0.6064 - dense_1_loss: 0.3977 - dropout_loss: 0.4173 - val_loss: 0.9674 - val_dense_1_loss: 0.8543 - val_dropout_loss: 0.2262 Epoch 4/5 1/3 [=========>....................] - ETA: 0s - loss: 0.7513 - dense_1_loss: 0.6000 - dropout_loss: 0.3028 3/3 [==============================] - 0s 5ms/step - loss: 0.8512 - dense_1_loss: 0.6557 - dropout_loss: 0.3911 - val_loss: 0.7176 - val_dense_1_loss: 0.6103 - val_dropout_loss: 0.2147 Epoch 5/5 1/3 [=========>....................] - ETA: 0s - loss: 0.8742 - dense_1_loss: 0.5716 - dropout_loss: 0.6052 3/3 [==============================] - 0s 37ms/step - loss: 0.8369 - dense_1_loss: 0.5515 - dropout_loss: 0.5709 - val_loss: 0.6706 - val_dense_1_loss: 0.5773 - val_dropout_loss: 0.1865 Epoch 1/5 1/12 [=>............................] - ETA: 0s - loss: 0.8565 - dense_1_loss: 0.5612 - dropout_loss: 0.5907 5/12 [===========>..................] - ETA: 0s - loss: 0.7895 - dense_1_loss: 0.5169 - dropout_loss: 0.5453 12/12 [==============================] - 0s 11ms/step - loss: 0.7347 - dense_1_loss: 0.4727 - dropout_loss: 0.5240 - val_loss: 0.6802 - val_dense_1_loss: 0.5844 - val_dropout_loss: 0.1915 Epoch 2/5 1/12 [=>............................] - ETA: 0s - loss: 1.0174 - dense_1_loss: 0.7099 - dropout_loss: 0.6151 12/12 [==============================] - 0s 10ms/step - loss: 0.8505 - dense_1_loss: 0.5927 - dropout_loss: 0.5156 - val_loss: 0.5632 - val_dense_1_loss: 0.4711 - val_dropout_loss: 0.1841 Epoch 3/5 1/12 [=>............................] - ETA: 0s - loss: 0.7463 - dense_1_loss: 0.5268 - dropout_loss: 0.4390 12/12 [==============================] - 0s 7ms/step - loss: 0.7836 - dense_1_loss: 0.5443 - dropout_loss: 0.4785 - val_loss: 0.6757 - val_dense_1_loss: 0.5987 - val_dropout_loss: 0.1540 Epoch 4/5 1/12 [=>............................] - ETA: 0s - loss: 0.6755 - dense_1_loss: 0.4811 - dropout_loss: 0.3887 12/12 [==============================] - 0s 9ms/step - loss: 0.6410 - dense_1_loss: 0.4230 - dropout_loss: 0.4358 - val_loss: 0.5837 - val_dense_1_loss: 0.5010 - val_dropout_loss: 0.1654 Epoch 5/5 1/12 [=>............................] - ETA: 0s - loss: 0.4936 - dense_1_loss: 0.3931 - dropout_loss: 0.2010 12/12 [==============================] - 0s 10ms/step - loss: 0.6831 - dense_1_loss: 0.4509 - dropout_loss: 0.4644 - val_loss: 0.5069 - val_dense_1_loss: 0.4276 - val_dropout_loss: 0.1585 Epoch 1/5 1/12 [=>............................] - ETA: 0s - loss: 0.8694 - dense_1_loss: 0.4631 - dropout_loss: 0.8126 ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:131: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:133: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:131: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:133: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING tensorflow:deprecation.py:506 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. =============================== warnings summary =============================== tests/keras/engine/test_training.py:1104 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:1104: DeprecationWarning: invalid escape sequence \d 'have one entry per model output. The model has \d ' tests/keras/engine/test_training.py:1109 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:1109: DeprecationWarning: invalid escape sequence \d match='The model has \d outputs, but you passed a single ' /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): keras/utils/data_utils.py:651 keras/utils/data_utils.py:651 keras/utils/data_utils.py:651 /home/user/BugsInPy/temp/projects/keras/keras/utils/data_utils.py:651: DeprecationWarning: `wait_time` is not used anymore. DeprecationWarning) /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/30be27653f737e13d505dcd8372bd58d/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 5.76s call tests/keras/engine/test_training.py::test_model_methods (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/engine/test_training.py::test_model_methods - ValueError: ... ======================= 1 failed, 14 warnings in 17.26s ======================== Using TensorFlow backend.
pytest tests/keras/engine/test_training.py::test_model_methods
2bfd1f2c950df5fc3f40b903c1966f1b0a48bee4
tests/keras/engine/test_training.py
keras-team__keras-22
keras-team/keras
diff --git a/keras/engine/input_layer.py b/keras/engine/input_layer.py index bc149168..632bf39e 100644 --- a/keras/engine/input_layer.py +++ b/keras/engine/input_layer.py @@ -42,6 +42,7 @@ class InputLayer(Layer): self.trainable = False self.built = True self.sparse = sparse + self.supports_masking = True if input_shape and batch_input_shape: raise ValueError('Only provide the input_shape OR '
diff --git a/tests/keras/layers/core_test.py b/tests/keras/layers/core_test.py index 1d3ac1967..dd60f5a46 100644 --- a/tests/keras/layers/core_test.py +++ b/tests/keras/layers/core_test.py @@ -5,6 +5,7 @@ from numpy.testing import assert_allclose from keras import backend as K from keras import layers from keras.models import Model +from keras.models import Sequential from keras.utils.test_utils import layer_test from keras.utils.test_utils import keras_test from keras import regularizers @@ -343,5 +344,30 @@ def test_activity_regularization(): model.compile('rmsprop', 'mse') +@keras_test +def test_sequential_as_downstream_of_masking_layer(): + + inputs = layers.Input(shape=(3, 4)) + x = layers.Masking(mask_value=0., input_shape=(3, 4))(inputs) + s = Sequential() + s.add(layers.Dense(5, input_shape=(4,))) + s.add(layers.Activation('relu')) + x = layers.wrappers.TimeDistributed(s)(x) + model = Model(inputs=inputs, outputs=x) + model.compile(optimizer='rmsprop', loss='mse') + model_input = np.random.randint(low=1, high=5, size=(10, 3, 4)) + for i in range(4): + model_input[i, i:, :] = 0. + model.fit(model_input, + np.random.random((10, 3, 5)), epochs=1, batch_size=6) + + mask_outputs = [model.layers[1].compute_mask(model.layers[1].input)] + mask_outputs += [model.layers[2].compute_mask(model.layers[2].input, mask_outputs[-1])] + func = K.function([model.input], mask_outputs) + mask_outputs_val = func([model_input]) + assert np.array_equal(mask_outputs_val[0], np.any(model_input, axis=-1)) + assert np.array_equal(mask_outputs_val[1], np.any(model_input, axis=-1)) + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [0] / gw1 [0] scheduling tests via LoadScheduling ==================================== ERRORS ==================================== _______________ ERROR collecting tests/keras/layers/core_test.py _______________ tests/keras/layers/core_test.py:5: in <module> from keras import backend as K keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. _______________ ERROR collecting tests/keras/layers/core_test.py _______________ tests/keras/layers/core_test.py:5: in <module> from keras import backend as K keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. =============================== warnings summary =============================== /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ ERROR tests/keras/layers/core_test.py - AttributeError: module 'keras_applica... ERROR tests/keras/layers/core_test.py - AttributeError: module 'keras_applica... ======================== 56 warnings, 2 errors in 2.38s ========================
pytest tests/keras/layers/core_test.py::test_sequential_as_downstream_of_masking_layer
54386efa549f850dff13f79fc3af67799a4e5d4f
tests/keras/layers/core_test.py
keras-team__keras-9
keras-team/keras
diff --git a/docs/autogen.py b/docs/autogen.py index e3786a92..85acc296 100644 --- a/docs/autogen.py +++ b/docs/autogen.py @@ -117,8 +117,8 @@ def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) - block = docstring[starting_point:(None if ending_point == -1 else - ending_point - 1)] + block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else + section_end)] # Place marker for later reinjection. docstring_slice = docstring[starting_point:section_end].replace(block, marker) docstring = (docstring[:starting_point]
diff --git a/tests/test_doc_auto_generation.py b/tests/test_doc_auto_generation.py index 31747ccaa..6cdb23f08 100644 --- a/tests/test_doc_auto_generation.py +++ b/tests/test_doc_auto_generation.py @@ -326,9 +326,33 @@ y = layer(x) '''} -def test_doc_lists(): - docstring = autogen.process_docstring(test_doc1['doc']) - assert markdown(docstring) == markdown(test_doc1['result']) +test_doc_with_arguments_as_last_block = { + 'doc': """Base class for recurrent layers. + + # Arguments + return_sequences: Boolean. Whether to return the last output + in the output sequence, or the full sequence. + return_state: Boolean. Whether to return the last state + in addition to the output. + """, + 'result': '''Base class for recurrent layers. + +__Arguments__ + +- __return_sequences__: Boolean. Whether to return the last output + in the output sequence, or the full sequence. +- __return_state__: Boolean. Whether to return the last state + in addition to the output. +'''} + + [email protected]('docs_descriptor', [ + test_doc1, + test_doc_with_arguments_as_last_block, +]) +def test_doc_lists(docs_descriptor): + docstring = autogen.process_docstring(docs_descriptor['doc']) + assert markdown(docstring) == markdown(docs_descriptor['result']) dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*.
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1] [gw0] [100%] FAILED tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1] =================================== FAILURES =================================== _______________________ test_doc_lists[docs_descriptor1] _______________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python docs_descriptor = {'doc': 'Base class for recurrent layers.\n\n # Arguments\n return_sequences: Boolean. Whether to return the...r the full sequence.\n- __return_state__: Boolean. Whether to return the last state\n in addition to the output.\n'} @pytest.mark.parametrize('docs_descriptor', [ test_doc1, test_doc_with_arguments_as_last_block, ]) def test_doc_lists(docs_descriptor): docstring = autogen.process_docstring(docs_descriptor['doc']) > assert markdown(docstring) == markdown(docs_descriptor['result']) E AssertionError: assert '<p>Base clas...e output.</p>' == '<p>Base clas....</li>\n</ul>' E <p>Base class for recurrent layers.</p> E <p><strong>Arguments</strong></p> E - <ul> E - <li><strong>return_sequences</strong>: Boolean. Whether to return the last output E ? ^^^^^^^^^^ --------- E + <p>return_sequences: Boolean. Whether to return the last output E ? ^... E E ...Full output truncated (12 lines hidden), use '-vv' to show tests/test_doc_auto_generation.py:355: AssertionError --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:102: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:102: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.03s call tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1] (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1] - ... ======================== 1 failed, 1 warning in 18.58s ========================= Using TensorFlow backend.
pytest tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1]
0cd3b07eb5de1aaaad84d1ff7f7c2ed7dab4b23c
tests/test_doc_auto_generation.py
keras-team__keras-7
keras-team/keras
diff --git a/keras/wrappers/scikit_learn.py b/keras/wrappers/scikit_learn.py index 6ebf6fc8..83c3e3c4 100644 --- a/keras/wrappers/scikit_learn.py +++ b/keras/wrappers/scikit_learn.py @@ -320,7 +320,7 @@ class KerasRegressor(BaseWrapper): Predictions. """ kwargs = self.filter_sk_params(Sequential.predict, kwargs) - return np.squeeze(self.model.predict(x, **kwargs)) + return np.squeeze(self.model.predict(x, **kwargs), axis=-1) def score(self, x, y, **kwargs): """Returns the mean loss on the given test data and labels.
diff --git a/tests/keras/wrappers/scikit_learn_test.py b/tests/keras/wrappers/scikit_learn_test.py index e64aebef2..8b180ff10 100644 --- a/tests/keras/wrappers/scikit_learn_test.py +++ b/tests/keras/wrappers/scikit_learn_test.py @@ -167,6 +167,24 @@ def assert_regression_works(reg): assert preds.shape == (num_test, ) +def test_regression_predict_shape_correct_num_test_0(): + assert_regression_predict_shape_correct(num_test=0) + + +def test_regression_predict_shape_correct_num_test_1(): + assert_regression_predict_shape_correct(num_test=1) + + +def assert_regression_predict_shape_correct(num_test): + reg = KerasRegressor( + build_fn=build_fn_reg, hidden_dims=hidden_dims, + batch_size=batch_size, epochs=epochs) + reg.fit(X_train, y_train, batch_size=batch_size, epochs=epochs) + + preds = reg.predict(X_test[:num_test], batch_size=batch_size) + assert preds.shape == (num_test, ) + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1 [gw0] [100%] FAILED tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1 =================================== FAILURES =================================== _______________ test_regression_predict_shape_correct_num_test_1 _______________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_regression_predict_shape_correct_num_test_1(): > assert_regression_predict_shape_correct(num_test=1) tests/keras/wrappers/scikit_learn_test.py:175: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ num_test = 1 def assert_regression_predict_shape_correct(num_test): reg = KerasRegressor( build_fn=build_fn_reg, hidden_dims=hidden_dims, batch_size=batch_size, epochs=epochs) reg.fit(X_train, y_train, batch_size=batch_size, epochs=epochs) preds = reg.predict(X_test[:num_test], batch_size=batch_size) > assert preds.shape == (num_test, ) E assert () == (1,) E Right contains one more item: 1 E Full diff: E - (1,) E + () tests/keras/wrappers/scikit_learn_test.py:185: AssertionError ----------------------------- Captured stdout call ----------------------------- Epoch 1/1 32/100 [========>.....................] - ETA: 0s - loss: 1.1518 - acc: 0.3438 100/100 [==============================] - 0s 5ms/step - loss: 1.2485 - acc: 0.2500 ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4343: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:997: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:984: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2919: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. 2023-07-15 04:14:55.116696: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 04:14:55.139449: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 04:14:55.143427: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55cc8808e7c0 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 04:14:55.143460: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 04:14:55.144741: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 04:14:55.144757: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 04:14:55.144778: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (8cd2fa7be075): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4343: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:997: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:984: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2919: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 1.08s call tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1 (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1 ======================== 1 failed, 5 warnings in 15.62s ======================== Using TensorFlow backend.
pytest tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1
26b620fb37c885d60183f83abc744f43775ce75a
tests/keras/wrappers/scikit_learn_test.py
keras-team__keras-34
keras-team/keras
diff --git a/keras/engine/training.py b/keras/engine/training.py index ea641c3a..44d7587b 100644 --- a/keras/engine/training.py +++ b/keras/engine/training.py @@ -2162,7 +2162,10 @@ class Model(Container): val_enqueuer.start(workers=workers, max_queue_size=max_queue_size) validation_generator = val_enqueuer.get() else: - validation_generator = validation_data + if isinstance(validation_data, Sequence): + validation_generator = iter(validation_data) + else: + validation_generator = validation_data else: if len(validation_data) == 2: val_x, val_y = validation_data @@ -2194,7 +2197,10 @@ class Model(Container): enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - output_generator = generator + if is_sequence: + output_generator = iter(generator) + else: + output_generator = generator callback_model.stop_training = False # Construct epoch logs. @@ -2366,7 +2372,10 @@ class Model(Container): enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - output_generator = generator + if is_sequence: + output_generator = iter(generator) + else: + output_generator = generator while steps_done < steps: generator_output = next(output_generator) @@ -2490,7 +2499,10 @@ class Model(Container): enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - output_generator = generator + if is_sequence: + output_generator = iter(generator) + else: + output_generator = generator if verbose == 1: progbar = Progbar(target=steps) diff --git a/keras/utils/data_utils.py b/keras/utils/data_utils.py index 514ad655..1edd5531 100644 --- a/keras/utils/data_utils.py +++ b/keras/utils/data_utils.py @@ -366,6 +366,12 @@ class Sequence(object): """ pass + def __iter__(self): + """Create an infinite generator that iterate over the Sequence.""" + while True: + for item in (self[i] for i in range(len(self))): + yield item + # Global variables to be shared across processes _SHARED_SEQUENCES = {}
diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index be7a59ac1..ab637e1c8 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -6,12 +6,21 @@ import numpy as np from keras.models import Sequential from keras.layers.core import Dense from keras.utils.test_utils import keras_test +from keras.utils import Sequence STEPS_PER_EPOCH = 100 STEPS = 100 WORKERS = 4 +class DummySequence(Sequence): + def __getitem__(self, idx): + return np.zeros([10, 2]), np.ones([10]) + + def __len__(self): + return 10 + + @pytest.fixture def in_tmpdir(tmpdir): """Runs a function in a temporary directory. @@ -175,6 +184,22 @@ def test_multiprocessing_training(): workers=0, use_multiprocessing=False) + # - For Sequence + model.fit_generator(DummySequence(), + steps_per_epoch=STEPS_PER_EPOCH, + validation_data=custom_generator(True), + validation_steps=1, + max_queue_size=10, + workers=0, + use_multiprocessing=True) + model.fit_generator(DummySequence(), + steps_per_epoch=STEPS_PER_EPOCH, + validation_data=custom_generator(True), + validation_steps=1, + max_queue_size=10, + workers=0, + use_multiprocessing=False) + # Test invalid use cases def invalid_generator(): while True:
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/test_multiprocessing.py::test_multiprocessing_training [gw0] [100%] FAILED tests/test_multiprocessing.py::test_multiprocessing_training =================================== FAILURES =================================== ________________________ test_multiprocessing_training _________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/bin/python @keras_test def test_multiprocessing_training(): arr_data = np.random.randint(0, 256, (50, 2)) arr_labels = np.random.randint(0, 2, 50) arr_weights = np.random.random(50) def custom_generator(use_weights=False): batch_size = 10 n_samples = 50 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size X = arr_data[start: end] y = arr_labels[start: end] if use_weights: w = arr_weights[start: end] yield X, y, w else: yield X, y # Build a NN model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') # - Produce data on 4 worker processes, consume on main process: # - Each worker process runs OWN copy of generator # - BUT on Windows, `multiprocessing` won't marshall generators across # process boundaries -> make sure `fit_generator()` raises ValueError # exception and does not attempt to run the generator. if os.name is 'nt': with pytest.raises(ValueError): model.fit_generator(custom_generator(), steps_per_epoch=STEPS_PER_EPOCH, epochs=1, verbose=1, validation_steps=None, max_queue_size=10, workers=WORKERS, use_multiprocessing=True) else: model.fit_generator(custom_generator(), steps_per_epoch=STEPS_PER_EPOCH, epochs=1, verbose=1, validation_steps=None, max_queue_size=10, workers=WORKERS, use_multiprocessing=True) # - Produce data on 4 worker threads, consume on main thread: # - All worker threads share the SAME generator model.fit_generator(custom_generator(), steps_per_epoch=STEPS_PER_EPOCH, epochs=1, verbose=1, validation_steps=None, max_queue_size=10, workers=WORKERS, use_multiprocessing=False) # - Produce data on 1 worker process, consume on main process: # - Worker process runs generator # - BUT on Windows, `multiprocessing` won't marshall generators across # process boundaries -> make sure `fit_generator()` raises ValueError # exception and does not attempt to run the generator. if os.name is 'nt': with pytest.raises(ValueError): model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=(arr_data[:10], arr_labels[:10], arr_weights[:10]), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=True) else: model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=(arr_data[:10], arr_labels[:10], arr_weights[:10]), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=True) # - Produce data on 1 worker thread, consume on main thread: # - Worker thread is the only thread running the generator model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=(arr_data[:10], arr_labels[:10], arr_weights[:10]), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=False) # - Produce data on 1 worker process, consume on main process: # - Worker process runs generator # - BUT on Windows, `multiprocessing` won't marshall generators across # process boundaries -> make sure `fit_generator()` raises ValueError # exception and does not attempt to run the generator. if os.name is 'nt': with pytest.raises(ValueError): model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=True) else: model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=True) # - Produce data on 1 worker thread AT A TIME, consume on main thread: # - Worker threads for training and validation run generator SEQUENTIALLY model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=1, use_multiprocessing=False) # - Produce and consume data without a queue on main thread # - Make sure the value of `use_multiprocessing` is ignored model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=0, use_multiprocessing=True) model.fit_generator(custom_generator(True), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=0, use_multiprocessing=False) # - For Sequence model.fit_generator(DummySequence(), steps_per_epoch=STEPS_PER_EPOCH, validation_data=custom_generator(True), validation_steps=1, max_queue_size=10, workers=0, > use_multiprocessing=True) tests/test_multiprocessing.py:194: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) keras/models.py:1253: in fit_generator initial_epoch=initial_epoch) keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <keras.engine.training.Model object at 0x7feb69a48ef0> generator = <test_multiprocessing.DummySequence object at 0x7feb6992f390> steps_per_epoch = 100, epochs = 1, verbose = 1 callbacks = <keras.callbacks.CallbackList object at 0x7feb69b48518> validation_data = <generator object test_multiprocessing_training.<locals>.custom_generator at 0x7feb69957b88> validation_steps = 1, class_weight = None, max_queue_size = 10, workers = 0 use_multiprocessing = True, shuffle = True, initial_epoch = 0 @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0): """Trains the model on data yielded batch-by-batch by a Python generator. The generator is run in parallel to the model, for efficiency. For instance, this allows you to do real-time data augmentation on images on CPU in parallel to training your model on GPU. The use of `keras.utils.Sequence` guarantees the ordering and guarantees the single use of every input per epoch when using `use_multiprocessing=True`. # Arguments generator: A generator or an instance of `Sequence` (`keras.utils.Sequence`) object in order to avoid duplicate data when using multiprocessing. The output of the generator must be either - a tuple `(inputs, targets)` - a tuple `(inputs, targets, sample_weights)`. This tuple (a single output of the generator) makes a single batch. Therefore, all arrays in this tuple must have the same length (equal to the size of this batch). Different batches may have different sizes. For example, the last batch of the epoch is commonly smaller than the others, if the size of the dataset is not divisible by the batch size. The generator is expected to loop over its data indefinitely. An epoch finishes when `steps_per_epoch` batches have been seen by the model. steps_per_epoch: Integer. Total number of steps (batches of samples) to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. epochs: Integer. Number of epochs to train the model. An epoch is an iteration over the entire data provided, as defined by `steps_per_epoch`. Note that in conjunction with `initial_epoch`, `epochs` is to be understood as "final epoch". The model is not trained for a number of iterations given by `epochs`, but merely until the epoch of index `epochs` is reached. verbose: Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during training. See [callbacks](/callbacks). validation_data: This can be either - a generator for the validation data - tuple `(x_val, y_val)` - tuple `(x_val, y_val, val_sample_weights)` on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `validation_data` generator before stopping. Optional for `Sequence`: if unspecified, will use the `len(validation_data)` as a number of steps. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. max_queue_size: Integer. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Maximum number of processes to spin up when using process based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. use_multiprocessing: Boolean. If True, use process based threading. If unspecified, `use_multiprocessing` will default to False. Note that because this implementation relies on multiprocessing, you should not pass non picklable arguments to the generator as they can't be passed easily to children processes. shuffle: Boolean. Whether to shuffle the training data in batch-sized chunks before each epoch. Only used with instances of `Sequence` (`keras.utils.Sequence`). initial_epoch: Integer. Epoch at which to start training (useful for resuming a previous training run). # Returns A `History` object. Its `History.history` attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable). # Example ```python def generate_arrays_from_file(path): while 1: with open(path) as f: for line in f: # create numpy arrays of input data # and labels, from each line in the file x1, x2, y = process_line(line) yield ({'input_1': x1, 'input_2': x2}, {'output': y}) model.fit_generator(generate_arrays_from_file('/my_file.txt'), steps_per_epoch=10000, epochs=10) ``` # Raises ValueError: In case the generator yields data in an invalid format. """ wait_time = 0.01 # in seconds epoch = initial_epoch do_validation = bool(validation_data) self._make_train_function() if do_validation: self._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps_per_epoch is None: if is_sequence: steps_per_epoch = len(generator) else: raise ValueError('`steps_per_epoch=None` is only valid for a' ' generator based on the `keras.utils.Sequence`' ' class. Please specify `steps_per_epoch` or use' ' the `keras.utils.Sequence` class.') # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isinstance(validation_data, Sequence)) if (val_gen and not isinstance(validation_data, Sequence) and not validation_steps): raise ValueError('`validation_steps=None` is only valid for a' ' generator based on the `keras.utils.Sequence`' ' class. Please specify `validation_steps` or use' ' the `keras.utils.Sequence` class.') # Prepare display labels. out_labels = self.metrics_names callback_metrics = out_labels + ['val_' + n for n in out_labels] # prepare callbacks self.history = cbks.History() _callbacks = [cbks.BaseLogger( stateful_metrics=self.stateful_metric_names)] if verbose: _callbacks.append( cbks.ProgbarLogger( count_mode='steps', stateful_metrics=self.stateful_metric_names)) _callbacks += (callbacks or []) + [self.history] callbacks = cbks.CallbackList(_callbacks) # it's possible to callback a different model than self: if hasattr(self, 'callback_model') and self.callback_model: callback_model = self.callback_model else: callback_model = self callbacks.set_model(callback_model) callbacks.set_params({ 'epochs': epochs, 'steps': steps_per_epoch, 'verbose': verbose, 'do_validation': do_validation, 'metrics': callback_metrics, }) callbacks.on_train_begin() enqueuer = None val_enqueuer = None try: if do_validation: if val_gen: if workers > 0: if isinstance(validation_data, Sequence): val_enqueuer = OrderedEnqueuer( validation_data, use_multiprocessing=use_multiprocessing) if validation_steps is None: validation_steps = len(validation_data) else: val_enqueuer = GeneratorEnqueuer( validation_data, use_multiprocessing=use_multiprocessing, wait_time=wait_time) val_enqueuer.start(workers=workers, max_queue_size=max_queue_size) validation_generator = val_enqueuer.get() else: validation_generator = validation_data else: if len(validation_data) == 2: val_x, val_y = validation_data val_sample_weight = None elif len(validation_data) == 3: val_x, val_y, val_sample_weight = validation_data else: raise ValueError('`validation_data` should be a tuple ' '`(val_x, val_y, val_sample_weight)` ' 'or `(val_x, val_y)`. Found: ' + str(validation_data)) val_x, val_y, val_sample_weights = self._standardize_user_data( val_x, val_y, val_sample_weight) val_data = val_x + val_y + val_sample_weights if self.uses_learning_phase and not isinstance(K.learning_phase(), int): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer(generator, use_multiprocessing=use_multiprocessing, shuffle=shuffle) else: enqueuer = GeneratorEnqueuer(generator, use_multiprocessing=use_multiprocessing, wait_time=wait_time) enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: output_generator = generator callback_model.stop_training = False # Construct epoch logs. epoch_logs = {} while epoch < epochs: callbacks.on_epoch_begin(epoch) steps_done = 0 batch_index = 0 while steps_done < steps_per_epoch: > generator_output = next(output_generator) E TypeError: 'DummySequence' object is not an iterator keras/engine/training.py:2207: TypeError ----------------------------- Captured stdout call ----------------------------- Epoch 1/1 1/100 [..............................] - ETA: 15s - loss: 36868.5742 15/100 [===>..........................] - ETA: 1s - loss: 27005.1152 38/100 [==========>...................] - ETA: 0s - loss: 26190.7296 55/100 [===============>..............] - ETA: 0s - loss: 25672.4717 80/100 [=======================>......] - ETA: 0s - loss: 24795.5524 100/100 [==============================] - 0s 4ms/step - loss: 23929.4405 Epoch 1/1 1/100 [..............................] - ETA: 0s - loss: 16415.7461 26/100 [======>.......................] - ETA: 0s - loss: 18616.0644 53/100 [==============>...............] - ETA: 0s - loss: 18537.7829 78/100 [======================>.......] - ETA: 0s - loss: 17575.5936 100/100 [==============================] - 0s 2ms/step - loss: 16976.1199 Epoch 1/1 1/100 [..............................] - ETA: 5s - loss: 7193.3384 15/100 [===>..........................] - ETA: 0s - loss: 5366.0518 34/100 [=========>....................] - ETA: 0s - loss: 5314.3505 54/100 [===============>..............] - ETA: 0s - loss: 5405.1500 73/100 [====================>.........] - ETA: 0s - loss: 5362.0688 85/100 [========================>.....] - ETA: 0s - loss: 5297.7706 100/100 [==============================] - 0s 4ms/step - loss: 5246.3170 - val_loss: 4795.6582 Epoch 1/1 1/100 [..............................] - ETA: 0s - loss: 6131.7529 25/100 [======>.......................] - ETA: 0s - loss: 4364.0050 42/100 [===========>..................] - ETA: 0s - loss: 4270.3753 76/100 [=====================>........] - ETA: 0s - loss: 4156.4289 100/100 [==============================] - 0s 2ms/step - loss: 4050.5813 - val_loss: 3634.0359 Epoch 1/1 1/100 [..............................] - ETA: 3s - loss: 4722.4326 20/100 [=====>........................] - ETA: 0s - loss: 3669.2873 38/100 [==========>...................] - ETA: 0s - loss: 3615.7818 60/100 [=================>............] - ETA: 0s - loss: 3337.2760 83/100 [=======================>......] - ETA: 0s - loss: 3164.8108 97/100 [============================>.] - ETA: 0s - loss: 3113.7656 100/100 [==============================] - 0s 3ms/step - loss: 3117.3142 - val_loss: 3066.5347 Epoch 1/1 1/100 [..............................] - ETA: 0s - loss: 3893.5527 18/100 [====>.........................] - ETA: 0s - loss: 2677.2934 50/100 [==============>...............] - ETA: 0s - loss: 2461.2871 85/100 [========================>.....] - ETA: 0s - loss: 2316.4719 100/100 [==============================] - 0s 2ms/step - loss: 2248.9253 - val_loss: 2635.5037 Epoch 1/1 1/100 [..............................] - ETA: 0s - loss: 1996.1188 38/100 [==========>...................] - ETA: 0s - loss: 1932.7970 76/100 [=====================>........] - ETA: 0s - loss: 1804.2855 100/100 [==============================] - 0s 1ms/step - loss: 1751.7773 - val_loss: 1687.2227 Epoch 1/1 1/100 [..............................] - ETA: 0s - loss: 786.9584 42/100 [===========>..................] - ETA: 0s - loss: 1340.0231 84/100 [========================>.....] - ETA: 0s - loss: 1271.1178 100/100 [==============================] - 0s 1ms/step - loss: 1211.6427 - val_loss: 1354.3267 Epoch 1/1 ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING:tensorflow:From /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. 2023-07-15 06:29:27.857469: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:29:27.861132: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:29:27.863418: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x557b9db4aa50 executing computations on platform Host. Devices: 2023-07-15 06:29:27.863439: I tensorflow/compiler/xla/service/service.cc:158] StreamExecutor device (0): <undefined>, <undefined> ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. =============================== warnings summary =============================== /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/50ed758a536fff6a0703bf56934e9ce8/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ keras/engine/training.py:2088 /home/user/BugsInPy/temp/projects/keras/keras/engine/training.py:2088: UserWarning: Using a generator with `use_multiprocessing=True` and multiple workers may duplicate your data. Please consider using the`keras.utils.Sequence class. UserWarning('Using a generator with `use_multiprocessing=True`' -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 2.84s call tests/test_multiprocessing.py::test_multiprocessing_training (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/test_multiprocessing.py::test_multiprocessing_training - TypeErr... ======================= 1 failed, 46 warnings in 13.76s ========================
pytest tests/test_multiprocessing.py::test_multiprocessing_training
7ef5244a2f1f7f7b76e3c804b82cbb20cdf4d139
tests/test_multiprocessing.py
keras-team__keras-28
keras-team/keras
diff --git a/keras/preprocessing/sequence.py b/keras/preprocessing/sequence.py index 03906c04..7bfe97a9 100644 --- a/keras/preprocessing/sequence.py +++ b/keras/preprocessing/sequence.py @@ -326,9 +326,15 @@ class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size + if self.start_index > self.end_index: + raise ValueError('`start_index+length=%i > end_index=%i` ' + 'is disallowed, as no part of the sequence ' + 'would be left to be used as current step.' + % (self.start_index, self.end_index)) + def __len__(self): return int(np.ceil( - (self.end_index - self.start_index) / + (self.end_index - self.start_index + 1) / (self.batch_size * self.stride))) def _empty_batch(self, num_rows): @@ -341,11 +347,11 @@ class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( - self.start_index, self.end_index, size=self.batch_size) + self.start_index, self.end_index + 1, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.arange(i, min(i + self.batch_size * - self.stride, self.end_index), self.stride) + self.stride, self.end_index + 1), self.stride) samples, targets = self._empty_batch(len(rows)) for j, row in enumerate(rows):
diff --git a/tests/keras/preprocessing/sequence_test.py b/tests/keras/preprocessing/sequence_test.py index b219baab6..c80a6536e 100644 --- a/tests/keras/preprocessing/sequence_test.py +++ b/tests/keras/preprocessing/sequence_test.py @@ -1,5 +1,7 @@ +from math import ceil + import numpy as np -from numpy.testing import assert_allclose +from numpy.testing import assert_allclose, assert_raises import pytest @@ -152,7 +154,7 @@ def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) - assert len(data_gen) == 5 + assert len(data_gen) == 6 assert (np.allclose(data_gen[0][0], np.array([[[10], [12], [14], [16], [18]], [[11], [13], [15], [17], [19]]]))) @@ -165,13 +167,76 @@ def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) - - assert len(data_gen) == 5 + assert len(data_gen) == 6 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2]), np.array(data[11:20:2])])) assert (np.allclose(data_gen[0][1], np.array([targets[20], targets[21]]))) + with assert_raises(ValueError) as context: + TimeseriesGenerator(data, targets, length=50) + error = str(context.exception) + assert '`start_index+length=50 > end_index=49` is disallowed' in error + + +def test_TimeSeriesGenerator_doesnt_miss_any_sample(): + x = np.array([[i] for i in range(10)]) + + for length in range(3, 10): + g = TimeseriesGenerator(x, x, + length=length, + batch_size=1) + expected = max(0, len(x) - length) + actual = len(g) + + assert expected == actual + + if len(g) > 0: + # All elements in range(length, 10) should be used as current step + expected = np.arange(length, 10).reshape(-1, 1) + + y = np.concatenate([g[ix][1] for ix in range(len(g))], axis=0) + assert_allclose(y, expected) + + x = np.array([[i] for i in range(23)]) + + strides = (1, 1, 5, 7, 3, 5, 3) + lengths = (3, 3, 4, 3, 1, 3, 7) + batch_sizes = (6, 6, 6, 5, 6, 6, 6) + shuffles = (False, True, True, False, False, False, False) + + for stride, length, batch_size, shuffle in zip(strides, + lengths, + batch_sizes, + shuffles): + g = TimeseriesGenerator(x, x, + length=length, + sampling_rate=1, + stride=stride, + start_index=0, + end_index=None, + shuffle=shuffle, + reverse=False, + batch_size=batch_size) + if shuffle: + # all batches have the same size when shuffle is True. + expected_sequences = ceil( + (23 - length) / float(batch_size * stride)) * batch_size + else: + # last batch will be different if `(samples - length) / stride` + # is not a multiple of `batch_size`. + expected_sequences = ceil((23 - length) / float(stride)) + + expected_batches = ceil(expected_sequences / float(batch_size)) + + y = [g[ix][1] for ix in range(len(g))] + + actual_sequences = sum(len(_y) for _y in y) + actual_batches = len(y) + + assert expected_sequences == actual_sequences + assert expected_batches == actual_batches + if __name__ == '__main__': pytest.main([__file__])
0 ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/preprocessing/sequence_test.py::test_TimeSeriesGenerator_doesnt_miss_any_sample [gw0] [100%] FAILED tests/keras/preprocessing/sequence_test.py::test_TimeSeriesGenerator_doesnt_miss_any_sample =================================== FAILURES =================================== _______________ test_TimeSeriesGenerator_doesnt_miss_any_sample ________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/bin/python def test_TimeSeriesGenerator_doesnt_miss_any_sample(): x = np.array([[i] for i in range(10)]) for length in range(3, 10): g = TimeseriesGenerator(x, x, length=length, batch_size=1) expected = max(0, len(x) - length) actual = len(g) > assert expected == actual E assert 7 == 6 E +7 E -6 tests/keras/preprocessing/sequence_test.py:192: AssertionError =============================== warnings summary =============================== /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/preprocessing/sequence_test.py::test_TimeSeriesGenerator_doesnt_miss_any_sample ======================== 1 failed, 27 warnings in 8.48s ======================== RUN EVERY COMMAND 1 pytest tests/keras/preprocessing/sequence_test.py::test_TimeSeriesGenerator_doesnt_miss_any_sample ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator [gw0] [100%] FAILED tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator =================================== FAILURES =================================== ___________________________ test_TimeseriesGenerator ___________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/bin/python def test_TimeseriesGenerator(): data = np.array([[i] for i in range(50)]) targets = np.array([[i] for i in range(50)]) data_gen = TimeseriesGenerator(data, targets, length=10, sampling_rate=2, batch_size=2) assert len(data_gen) == 20 assert (np.allclose(data_gen[0][0], np.array([[[0], [2], [4], [6], [8]], [[1], [3], [5], [7], [9]]]))) assert (np.allclose(data_gen[0][1], np.array([[10], [11]]))) assert (np.allclose(data_gen[1][0], np.array([[[2], [4], [6], [8], [10]], [[3], [5], [7], [9], [11]]]))) assert (np.allclose(data_gen[1][1], np.array([[12], [13]]))) data_gen = TimeseriesGenerator(data, targets, length=10, sampling_rate=2, reverse=True, batch_size=2) assert len(data_gen) == 20 assert (np.allclose(data_gen[0][0], np.array([[[8], [6], [4], [2], [0]], [[9], [7], [5], [3], [1]]]))) assert (np.allclose(data_gen[0][1], np.array([[10], [11]]))) data_gen = TimeseriesGenerator(data, targets, length=10, sampling_rate=2, shuffle=True, batch_size=1) batch = data_gen[0] r = batch[1][0][0] assert (np.allclose(batch[0], np.array([[[r - 10], [r - 8], [r - 6], [r - 4], [r - 2]]]))) assert (np.allclose(batch[1], np.array([[r], ]))) data_gen = TimeseriesGenerator(data, targets, length=10, sampling_rate=2, stride=2, batch_size=2) assert len(data_gen) == 10 assert (np.allclose(data_gen[1][0], np.array([[[4], [6], [8], [10], [12]], [[6], [8], [10], [12], [14]]]))) assert (np.allclose(data_gen[1][1], np.array([[14], [16]]))) data_gen = TimeseriesGenerator(data, targets, length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) > assert len(data_gen) == 6 E assert 5 == 6 E +5 E -6 tests/keras/preprocessing/sequence_test.py:157: AssertionError =============================== warnings summary =============================== /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/dbe8313bd2bb0305ed3f6515aa4d20dc/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator ======================== 1 failed, 26 warnings in 4.06s ========================
pytest tests/keras/preprocessing/sequence_test.py::test_TimeSeriesGenerator_doesnt_miss_any_sample pytest tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator
6171b3656ebd9b6038f709ba83f7475de284ba4e
tests/keras/preprocessing/sequence_test.py
keras-team__keras-12
keras-team/keras
0 ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] [gw1] [100%] PASSED tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.31s call tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] 0.01s setup tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] (0.00 durations hidden. Use -vv to show these durations.) ======================== 1 passed, 2 warnings in 7.80s ========================= Using TensorFlow backend. RUN EVERY COMMAND 1 pytest tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape2] [gw0] [100%] PASSED tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape2] =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.12s call tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape2] 0.01s teardown tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape2] (0.00 durations hidden. Use -vv to show these durations.) ======================== 1 passed, 2 warnings in 8.36s ========================= Using TensorFlow backend.
pytest tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape1] pytest tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness[shape2]
6dff721a3a8755356b2e89d02ef63ad8ab38ec95
tests/keras/metrics_test.py
keras-team__keras-27
keras-team/keras
diff --git a/keras/layers/wrappers.py b/keras/layers/wrappers.py index c4afab1b..3bf489d1 100644 --- a/keras/layers/wrappers.py +++ b/keras/layers/wrappers.py @@ -487,12 +487,24 @@ class Bidirectional(Wrapper): return self.forward_layer.updates + self.backward_layer.updates return [] + def get_updates_for(self, inputs=None): + forward_updates = self.forward_layer.get_updates_for(inputs) + backward_updates = self.backward_layer.get_updates_for(inputs) + return (super(Wrapper, self).get_updates_for(inputs) + + forward_updates + backward_updates) + @property def losses(self): if hasattr(self.forward_layer, 'losses'): return self.forward_layer.losses + self.backward_layer.losses return [] + def get_losses_for(self, inputs=None): + forward_losses = self.forward_layer.get_losses_for(inputs) + backward_losses = self.backward_layer.get_losses_for(inputs) + return (super(Wrapper, self).get_losses_for(inputs) + + forward_losses + backward_losses) + @property def constraints(self): constraints = {}
diff --git a/tests/keras/layers/wrappers_test.py b/tests/keras/layers/wrappers_test.py index 4407625b7..17f7b1e97 100644 --- a/tests/keras/layers/wrappers_test.py +++ b/tests/keras/layers/wrappers_test.py @@ -556,5 +556,39 @@ def test_Bidirectional_trainable(): assert len(layer.trainable_weights) == 6 +@keras_test +def test_Bidirectional_updates(): + x = Input(shape=(3, 2)) + layer = wrappers.Bidirectional(layers.SimpleRNN(3)) + assert len(layer.updates) == 0 + assert len(layer.get_updates_for(None)) == 0 + assert len(layer.get_updates_for(x)) == 0 + layer.forward_layer.add_update(0, inputs=x) + layer.forward_layer.add_update(1, inputs=None) + layer.backward_layer.add_update(0, inputs=x) + layer.backward_layer.add_update(1, inputs=None) + assert len(layer.updates) == 4 + assert len(layer.get_updates_for(None)) == 2 + assert len(layer.get_updates_for(x)) == 2 + + +@keras_test +def test_Bidirectional_losses(): + x = Input(shape=(3, 2)) + layer = wrappers.Bidirectional( + layers.SimpleRNN(3, kernel_regularizer='l1', bias_regularizer='l1')) + _ = layer(x) + assert len(layer.losses) == 4 + assert len(layer.get_losses_for(None)) == 4 + assert len(layer.get_losses_for(x)) == 0 + layer.forward_layer.add_loss(0, inputs=x) + layer.forward_layer.add_loss(1, inputs=None) + layer.backward_layer.add_loss(0, inputs=x) + layer.backward_layer.add_loss(1, inputs=None) + assert len(layer.losses) == 8 + assert len(layer.get_losses_for(None)) == 6 + assert len(layer.get_losses_for(x)) == 2 + + if __name__ == '__main__': pytest.main([__file__])
0 ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/wrappers_test.py::test_Bidirectional_updates [gw0] [100%] FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_updates =================================== FAILURES =================================== __________________________ test_Bidirectional_updates __________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/bin/python @keras_test def test_Bidirectional_updates(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional(layers.SimpleRNN(3)) assert len(layer.updates) == 0 assert len(layer.get_updates_for(None)) == 0 assert len(layer.get_updates_for(x)) == 0 layer.forward_layer.add_update(0, inputs=x) layer.forward_layer.add_update(1, inputs=None) layer.backward_layer.add_update(0, inputs=x) layer.backward_layer.add_update(1, inputs=None) assert len(layer.updates) == 4 > assert len(layer.get_updates_for(None)) == 2 E assert 1 == 2 E +1 E -2 tests/keras/layers/wrappers_test.py:571: AssertionError =============================== warnings summary =============================== /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.04s call tests/keras/layers/wrappers_test.py::test_Bidirectional_updates (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_updates - asse... ======================= 1 failed, 27 warnings in 11.86s ======================== RUN EVERY COMMAND 1 pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_updates ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/wrappers_test.py::test_Bidirectional_losses [gw0] [100%] FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_losses =================================== FAILURES =================================== __________________________ test_Bidirectional_losses ___________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/bin/python @keras_test def test_Bidirectional_losses(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional( layers.SimpleRNN(3, kernel_regularizer='l1', bias_regularizer='l1')) _ = layer(x) assert len(layer.losses) == 4 > assert len(layer.get_losses_for(None)) == 4 E assert 2 == 4 E +2 E -4 tests/keras/layers/wrappers_test.py:582: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. =============================== warnings summary =============================== /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/ed5a9063c4bedeafb0671856da27ae76/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.36s call tests/keras/layers/wrappers_test.py::test_Bidirectional_losses (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_losses - asser... ======================== 1 failed, 26 warnings in 4.98s ========================
pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_updates pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_losses
49f5b931410bc2e56378f20a15e8ac919e0efb88
tests/keras/layers/wrappers_test.py
keras-team__keras-41
keras-team/keras
diff --git a/keras/utils/data_utils.py b/keras/utils/data_utils.py index ce1a60ac..bc0d87ce 100644 --- a/keras/utils/data_utils.py +++ b/keras/utils/data_utils.py @@ -11,6 +11,7 @@ import sys import tarfile import threading import time +import traceback import zipfile from abc import abstractmethod from multiprocessing.pool import ThreadPool @@ -553,7 +554,7 @@ class OrderedEnqueuer(SequenceEnqueuer): yield inputs except Exception as e: self.stop() - raise StopIteration(e) + six.raise_from(StopIteration(e), e) def _send_sequence(self): """Send current Sequence to all workers.""" @@ -614,6 +615,7 @@ class GeneratorEnqueuer(SequenceEnqueuer): self._use_multiprocessing = use_multiprocessing self._threads = [] self._stop_event = None + self._manager = None self.queue = None self.seed = seed @@ -631,18 +633,27 @@ class GeneratorEnqueuer(SequenceEnqueuer): try: if self._use_multiprocessing or self.queue.qsize() < max_queue_size: generator_output = next(self._generator) - self.queue.put(generator_output) + self.queue.put((True, generator_output)) else: time.sleep(self.wait_time) except StopIteration: break - except Exception: + except Exception as e: + # Can't pick tracebacks. + # As a compromise, print the traceback and pickle None instead. + if self._use_multiprocessing: + traceback.print_exc() + setattr(e, '__traceback__', None) + elif not hasattr(e, '__traceback__'): + setattr(e, '__traceback__', sys.exc_info()[2]) + self.queue.put((False, e)) self._stop_event.set() - raise + break try: if self._use_multiprocessing: - self.queue = multiprocessing.Queue(maxsize=max_queue_size) + self._manager = multiprocessing.Manager() + self.queue = self._manager.Queue(maxsize=max_queue_size) self._stop_event = multiprocessing.Event() else: self.queue = queue.Queue() @@ -686,9 +697,8 @@ class GeneratorEnqueuer(SequenceEnqueuer): else: thread.join(timeout) - if self._use_multiprocessing: - if self.queue is not None: - self.queue.close() + if self._manager: + self._manager.shutdown() self._threads = [] self._stop_event = None @@ -704,12 +714,22 @@ class GeneratorEnqueuer(SequenceEnqueuer): """ while self.is_running(): if not self.queue.empty(): - inputs = self.queue.get() - if inputs is not None: - yield inputs + success, value = self.queue.get() + # Rethrow any exceptions found in the queue + if not success: + six.reraise(value.__class__, value, value.__traceback__) + # Yield regular values + if value is not None: + yield value else: all_finished = all([not thread.is_alive() for thread in self._threads]) if all_finished and self.queue.empty(): raise StopIteration() else: time.sleep(self.wait_time) + + # Make sure to rethrow the first exception in the queue, if any + while not self.queue.empty(): + success, value = self.queue.get() + if not success: + six.reraise(value.__class__, value, value.__traceback__) diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index 235c26a2..9b7a1632 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -232,7 +232,7 @@ def test_multiprocessing_fit_error(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (50, 2)), - np.random.randint(batch_size, 2, 50)) + np.random.randint(batch_size, 12, 50)) raise RuntimeError model = Sequential() @@ -241,13 +241,13 @@ def test_multiprocessing_fit_error(): samples = batch_size * (good_batches + 1) - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.fit_generator( custom_generator(), samples, 1, workers=4, use_multiprocessing=True, ) - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.fit_generator( custom_generator(), samples, 1, use_multiprocessing=False, @@ -258,25 +258,26 @@ def test_multiprocessing_fit_error(): def test_multiprocessing_evaluate_error(): batch_size = 10 good_batches = 3 + workers = 4 def custom_generator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (50, 2)), - np.random.randint(batch_size, 2, 50)) + np.random.randint(batch_size, 12, 50)) raise RuntimeError model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.evaluate_generator( - custom_generator(), good_batches + 1, 1, - workers=4, use_multiprocessing=True, + custom_generator(), good_batches * workers + 1, 1, + workers=workers, use_multiprocessing=True, ) - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.evaluate_generator( custom_generator(), good_batches + 1, 1, use_multiprocessing=False, @@ -299,13 +300,13 @@ def test_multiprocessing_predict_error(): model.add(Dense(1, input_shape=(5,))) model.compile(loss='mse', optimizer='adadelta') - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.predict_generator( custom_generator(), good_batches * workers + 1, 1, workers=workers, use_multiprocessing=True, ) - with pytest.raises(StopIteration): + with pytest.raises(RuntimeError): model.predict_generator( custom_generator(), good_batches + 1, 1, use_multiprocessing=False,
diff --git a/tests/keras/utils/data_utils_test.py b/tests/keras/utils/data_utils_test.py index 753330e41..f83ea6ec7 100644 --- a/tests/keras/utils/data_utils_test.py +++ b/tests/keras/utils/data_utils_test.py @@ -182,7 +182,7 @@ def test_generator_enqueuer_fail_threads(): FaultSequence()), use_multiprocessing=False) enqueuer.start(3, 10) gen_output = enqueuer.get() - with pytest.raises(StopIteration): + with pytest.raises(IndexError): next(gen_output) @@ -191,7 +191,7 @@ def test_generator_enqueuer_fail_processes(): FaultSequence()), use_multiprocessing=True) enqueuer.start(3, 10) gen_output = enqueuer.get() - with pytest.raises(StopIteration): + with pytest.raises(IndexError): next(gen_output)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads Exception in thread Thread-1: Traceback (most recent call last): File "/opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/user/BugsInPy/temp/projects/keras/keras/utils/data_utils.py", line 633, in data_generator_task generator_output = next(self._generator) File "/home/user/BugsInPy/temp/projects/keras/tests/keras/utils/data_utils_test.py", line 97, in __next__ return self.next() File "/home/user/BugsInPy/temp/projects/keras/tests/keras/utils/data_utils_test.py", line 101, in next return next(self.it) File "/home/user/BugsInPy/temp/projects/keras/tests/keras/utils/data_utils_test.py", line 143, in create_generator_from_sequence_threads yield ds[i] File "/home/user/BugsInPy/temp/projects/keras/tests/keras/utils/data_utils_test.py", line 131, in __getitem__ raise IndexError(item, 'is not present') IndexError: (0, 'is not present') [gw0] [100%] FAILED tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads =================================== FAILURES =================================== _____________________ test_generator_enqueuer_fail_threads _____________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python def test_generator_enqueuer_fail_threads(): enqueuer = GeneratorEnqueuer(create_generator_from_sequence_threads( FaultSequence()), use_multiprocessing=False) enqueuer.start(3, 10) gen_output = enqueuer.get() with pytest.raises(IndexError): > next(gen_output) E StopIteration tests/keras/utils/data_utils_test.py:186: StopIteration =============================== warnings summary =============================== /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:15 keras/callbacks.py:15 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:15: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.02s call tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads ======================== 1 failed, 55 warnings in 3.99s ========================
pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads
a27b4a51f4880ad3a7669531b667c1ef44b173ef
tests/keras/utils/data_utils_test.py
keras-team__keras-30
keras-team/keras
diff --git a/keras/engine/training.py b/keras/engine/training.py index c6691017..78be752b 100644 --- a/keras/engine/training.py +++ b/keras/engine/training.py @@ -2212,7 +2212,11 @@ class Model(Container): str(generator_output)) # build batch logs batch_logs = {} - if isinstance(x, list): + if x is None or len(x) == 0: + # Handle data tensors support when no input given + # step-size = 1 for data tensors + batch_size = 1 + elif isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0] @@ -2399,7 +2403,11 @@ class Model(Container): outs = [outs] outs_per_batch.append(outs) - if isinstance(x, list): + if x is None or len(x) == 0: + # Handle data tensors support when no input given + # step-size = 1 for data tensors + batch_size = 1 + elif isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0]
diff --git a/tests/keras/engine/test_training.py b/tests/keras/engine/test_training.py index 6854ffaec..7772883e4 100644 --- a/tests/keras/engine/test_training.py +++ b/tests/keras/engine/test_training.py @@ -867,6 +867,20 @@ def test_model_with_external_loss(): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) + # define a generator to produce x=None and y=None + def data_tensors_generator(): + while True: + yield (None, None) + + generator = data_tensors_generator() + + # test fit_generator for framework-native data tensors + out = model.fit_generator(generator, epochs=1, + steps_per_epoch=3) + + # test evaluate_generator for framework-native data tensors + out = model.evaluate_generator(generator, steps=3) + # test fit with validation data with pytest.raises(ValueError): out = model.fit(None, None,
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/engine/test_training.py::test_model_with_external_loss [gw1] [100%] FAILED tests/keras/engine/test_training.py::test_model_with_external_loss =================================== FAILURES =================================== ________________________ test_model_with_external_loss _________________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/bin/python @keras_test @pytest.mark.skipif((K.backend() == 'cntk'), reason='cntk does not support external loss yet') def test_model_with_external_loss(): # None loss, only regularization loss. a = Input(shape=(3,), name='input_a') a_2 = Dense(4, name='dense_1', kernel_regularizer='l1', bias_regularizer='l2')(a) dp = Dropout(0.5, name='dropout') a_3 = dp(a_2) model = Model(a, [a_2, a_3]) optimizer = 'rmsprop' loss = None model.compile(optimizer, loss, metrics=['mae']) input_a_np = np.random.random((10, 3)) # test train_on_batch out = model.train_on_batch(input_a_np, None) out = model.test_on_batch(input_a_np, None) # fit out = model.fit(input_a_np, None) # evaluate out = model.evaluate(input_a_np, None) # No dropout, external loss. a = Input(shape=(3,), name='input_a') a_2 = Dense(4, name='dense_1')(a) a_3 = Dense(4, name='dense_2')(a) model = Model(a, [a_2, a_3]) model.add_loss(K.mean(a_3 + a_2)) optimizer = 'rmsprop' loss = None model.compile(optimizer, loss, metrics=['mae']) # test train_on_batch out = model.train_on_batch(input_a_np, None) out = model.test_on_batch(input_a_np, None) # fit out = model.fit(input_a_np, None) # evaluate out = model.evaluate(input_a_np, None) # Test fit with no external data at all. if K.backend() == 'tensorflow': import tensorflow as tf a = Input(tensor=tf.Variable(input_a_np, dtype=tf.float32)) a_2 = Dense(4, name='dense_1')(a) a_2 = Dropout(0.5, name='dropout')(a_2) model = Model(a, a_2) model.add_loss(K.mean(a_2)) model.compile(optimizer='rmsprop', loss=None, metrics=['mean_squared_error']) # test train_on_batch out = model.train_on_batch(None, None) out = model.test_on_batch(None, None) out = model.predict_on_batch(None) # test fit with pytest.raises(ValueError): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # define a generator to produce x=None and y=None def data_tensors_generator(): while True: yield (None, None) generator = data_tensors_generator() # test fit_generator for framework-native data tensors out = model.fit_generator(generator, epochs=1, > steps_per_epoch=3) tests/keras/engine/test_training.py:879: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <keras.engine.training.Model object at 0x7fa63038c0f0> generator = <generator object test_model_with_external_loss.<locals>.data_tensors_generator at 0x7fa632d367c8> steps_per_epoch = 3, epochs = 1, verbose = 1 callbacks = <keras.callbacks.CallbackList object at 0x7fa6301137f0> validation_data = None, validation_steps = None, class_weight = None max_queue_size = 10, workers = 1, use_multiprocessing = False, shuffle = True initial_epoch = 0 @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0): """Trains the model on data generated batch-by-batch by a Python generator or an instance of `Sequence`. The generator is run in parallel to the model, for efficiency. For instance, this allows you to do real-time data augmentation on images on CPU in parallel to training your model on GPU. The use of `keras.utils.Sequence` guarantees the ordering and guarantees the single use of every input per epoch when using `use_multiprocessing=True`. # Arguments generator: A generator or an instance of `Sequence` (`keras.utils.Sequence`) object in order to avoid duplicate data when using multiprocessing. The output of the generator must be either - a tuple `(inputs, targets)` - a tuple `(inputs, targets, sample_weights)`. This tuple (a single output of the generator) makes a single batch. Therefore, all arrays in this tuple must have the same length (equal to the size of this batch). Different batches may have different sizes. For example, the last batch of the epoch is commonly smaller than the others, if the size of the dataset is not divisible by the batch size. The generator is expected to loop over its data indefinitely. An epoch finishes when `steps_per_epoch` batches have been seen by the model. steps_per_epoch: Integer. Total number of steps (batches of samples) to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. epochs: Integer. Number of epochs to train the model. An epoch is an iteration over the entire data provided, as defined by `steps_per_epoch`. Note that in conjunction with `initial_epoch`, `epochs` is to be understood as "final epoch". The model is not trained for a number of iterations given by `epochs`, but merely until the epoch of index `epochs` is reached. verbose: Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during training. See [callbacks](/callbacks). validation_data: This can be either - a generator for the validation data - tuple `(x_val, y_val)` - tuple `(x_val, y_val, val_sample_weights)` on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `validation_data` generator before stopping at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(validation_data)` as a number of steps. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. max_queue_size: Integer. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. use_multiprocessing: Boolean. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. shuffle: Boolean. Whether to shuffle the order of the batches at the beginning of each epoch. Only used with instances of `Sequence` (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not `None`. initial_epoch: Integer. Epoch at which to start training (useful for resuming a previous training run). # Returns A `History` object. Its `History.history` attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable). # Raises ValueError: In case the generator yields data in an invalid format. # Example ```python def generate_arrays_from_file(path): while True: with open(path) as f: for line in f: # create numpy arrays of input data # and labels, from each line in the file x1, x2, y = process_line(line) yield ({'input_1': x1, 'input_2': x2}, {'output': y}) model.fit_generator(generate_arrays_from_file('/my_file.txt'), steps_per_epoch=10000, epochs=10) ``` """ wait_time = 0.01 # in seconds epoch = initial_epoch do_validation = bool(validation_data) self._make_train_function() if do_validation: self._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps_per_epoch is None: if is_sequence: steps_per_epoch = len(generator) else: raise ValueError('`steps_per_epoch=None` is only valid for a' ' generator based on the `keras.utils.Sequence`' ' class. Please specify `steps_per_epoch` or use' ' the `keras.utils.Sequence` class.') # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isinstance(validation_data, Sequence)) if (val_gen and not isinstance(validation_data, Sequence) and not validation_steps): raise ValueError('`validation_steps=None` is only valid for a' ' generator based on the `keras.utils.Sequence`' ' class. Please specify `validation_steps` or use' ' the `keras.utils.Sequence` class.') # Prepare display labels. out_labels = self.metrics_names callback_metrics = out_labels + ['val_' + n for n in out_labels] # prepare callbacks self.history = cbks.History() _callbacks = [cbks.BaseLogger( stateful_metrics=self.stateful_metric_names)] if verbose: _callbacks.append( cbks.ProgbarLogger( count_mode='steps', stateful_metrics=self.stateful_metric_names)) _callbacks += (callbacks or []) + [self.history] callbacks = cbks.CallbackList(_callbacks) # it's possible to callback a different model than self: if hasattr(self, 'callback_model') and self.callback_model: callback_model = self.callback_model else: callback_model = self callbacks.set_model(callback_model) callbacks.set_params({ 'epochs': epochs, 'steps': steps_per_epoch, 'verbose': verbose, 'do_validation': do_validation, 'metrics': callback_metrics, }) callbacks.on_train_begin() enqueuer = None val_enqueuer = None try: if do_validation and not val_gen: # Prepare data for validation if len(validation_data) == 2: val_x, val_y = validation_data val_sample_weight = None elif len(validation_data) == 3: val_x, val_y, val_sample_weight = validation_data else: raise ValueError('`validation_data` should be a tuple ' '`(val_x, val_y, val_sample_weight)` ' 'or `(val_x, val_y)`. Found: ' + str(validation_data)) val_x, val_y, val_sample_weights = self._standardize_user_data( val_x, val_y, val_sample_weight) val_data = val_x + val_y + val_sample_weights if self.uses_learning_phase and not isinstance(K.learning_phase(), int): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer(generator, use_multiprocessing=use_multiprocessing, shuffle=shuffle) else: enqueuer = GeneratorEnqueuer(generator, use_multiprocessing=use_multiprocessing, wait_time=wait_time) enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = iter(generator) else: output_generator = generator callback_model.stop_training = False # Construct epoch logs. epoch_logs = {} while epoch < epochs: for m in self.metrics: if isinstance(m, Layer) and m.stateful: m.reset_states() callbacks.on_epoch_begin(epoch) steps_done = 0 batch_index = 0 while steps_done < steps_per_epoch: generator_output = next(output_generator) if not hasattr(generator_output, '__len__'): raise ValueError('Output of generator should be ' 'a tuple `(x, y, sample_weight)` ' 'or `(x, y)`. Found: ' + str(generator_output)) if len(generator_output) == 2: x, y = generator_output sample_weight = None elif len(generator_output) == 3: x, y, sample_weight = generator_output else: raise ValueError('Output of generator should be ' 'a tuple `(x, y, sample_weight)` ' 'or `(x, y)`. Found: ' + str(generator_output)) # build batch logs batch_logs = {} if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0] else: > batch_size = x.shape[0] E AttributeError: 'NoneType' object has no attribute 'shape' keras/engine/training.py:2220: AttributeError ----------------------------- Captured stdout call ----------------------------- Epoch 1/1 10/10 [==============================] - 0s 84us/step - loss: 0.0574 10/10 [==============================] - 0s 38us/step Epoch 1/1 10/10 [==============================] - 0s 93us/step - loss: -0.0669 10/10 [==============================] - 0s 35us/step Epoch 1/1 1/1 [==============================] - 0s 820us/step - loss: 0.1175 Epoch 1/1 ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3141: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. 2023-07-15 06:12:56.358073: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:12:56.363554: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:12:56.375518: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x558b73b47470 executing computations on platform Host. Devices: 2023-07-15 06:12:56.375569: I tensorflow/compiler/xla/service/service.cc:158] StreamExecutor device (0): <undefined>, <undefined> ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING tensorflow:deprecation.py:506 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3141: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. =============================== warnings summary =============================== /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:573 /opt/conda/envs/91f454ccae25459b57a9f2959f457e5b/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:573: DeprecationWarning: np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead append_fn(tensor_proto, proto_values) tests/keras/engine/test_training.py:814 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:814: UserWarning: Output "dense_1" missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "dense_1" during training. model.compile(optimizer, loss, metrics=['mae']) tests/keras/engine/test_training.py:814 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:814: UserWarning: Output "dropout" missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "dropout" during training. model.compile(optimizer, loss, metrics=['mae']) tests/keras/engine/test_training.py:836 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:836: UserWarning: Output "dense_1" missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "dense_1" during training. model.compile(optimizer, loss, metrics=['mae']) tests/keras/engine/test_training.py:836 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:836: UserWarning: Output "dense_2" missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "dense_2" during training. model.compile(optimizer, loss, metrics=['mae']) tests/keras/engine/test_training.py:858 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:858: UserWarning: Output "dropout" missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "dropout" during training. metrics=['mean_squared_error']) -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 1.86s call tests/keras/engine/test_training.py::test_model_with_external_loss (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/engine/test_training.py::test_model_with_external_loss - A... ======================= 1 failed, 51 warnings in 12.03s ========================
pytest tests/keras/engine/test_training.py::test_model_with_external_loss
c08ef613af27da896cee168daeee5c6fad1980b6
tests/keras/engine/test_training.py
keras-team__keras-33
keras-team/keras
diff --git a/keras/preprocessing/text.py b/keras/preprocessing/text.py index 8264c1a6..6bd17435 100644 --- a/keras/preprocessing/text.py +++ b/keras/preprocessing/text.py @@ -38,12 +38,21 @@ def text_to_word_sequence(text, if lower: text = text.lower() - if sys.version_info < (3,) and isinstance(text, unicode): - translate_map = dict((ord(c), unicode(split)) for c in filters) + if sys.version_info < (3,): + if isinstance(text, unicode): + translate_map = dict((ord(c), unicode(split)) for c in filters) + text = text.translate(translate_map) + elif len(split) == 1: + translate_map = maketrans(filters, split * len(filters)) + text = text.translate(translate_map) + else: + for c in filters: + text = text.replace(c, split) else: - translate_map = maketrans(filters, split * len(filters)) + translate_dict = dict((c, split) for c in filters) + translate_map = maketrans(translate_dict) + text = text.translate(translate_map) - text = text.translate(translate_map) seq = text.split(split) return [i for i in seq if i]
diff --git a/tests/keras/preprocessing/text_test.py b/tests/keras/preprocessing/text_test.py index 8d5ffb2f7..65fbdbb37 100644 --- a/tests/keras/preprocessing/text_test.py +++ b/tests/keras/preprocessing/text_test.py @@ -73,11 +73,21 @@ def test_text_to_word_sequence(): assert text_to_word_sequence(text) == ['hello', 'world'] +def test_text_to_word_sequence_multichar_split(): + text = 'hello!stop?world!' + assert text_to_word_sequence(text, split='stop') == ['hello', 'world'] + + def test_text_to_word_sequence_unicode(): text = u'ali! veli? kırk dokuz elli' assert text_to_word_sequence(text) == [u'ali', u'veli', u'kırk', u'dokuz', u'elli'] +def test_text_to_word_sequence_unicode_multichar_split(): + text = u'ali!stopveli?stopkırkstopdokuzstopelli' + assert text_to_word_sequence(text, split='stop') == [u'ali', u'veli', u'kırk', u'dokuz', u'elli'] + + def test_tokenizer_unicode(): texts = [u'ali veli kırk dokuz elli', u'ali veli kırk dokuz elli veli kırk dokuz'] tokenizer = Tokenizer(num_words=5)
0 ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_multichar_split [gw0] [100%] FAILED tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_multichar_split =================================== FAILURES =================================== __________________ test_text_to_word_sequence_multichar_split __________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/bin/python def test_text_to_word_sequence_multichar_split(): text = 'hello!stop?world!' > assert text_to_word_sequence(text, split='stop') == ['hello', 'world'] tests/keras/preprocessing/text_test.py:78: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ text = 'hello!stop?world!', filters = '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' lower = True, split = 'stop' def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" "): """Converts a text to a sequence of words (or tokens). # Arguments text: Input text (string). filters: Sequence of characters to filter out. lower: Whether to convert the input to lowercase. split: Sentence split marker (string). # Returns A list of words (or tokens). """ if lower: text = text.lower() if sys.version_info < (3,) and isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) else: > translate_map = maketrans(filters, split * len(filters)) E ValueError: the first two maketrans arguments must have equal length keras/preprocessing/text.py:44: ValueError =============================== warnings summary =============================== /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_multichar_split ======================= 1 failed, 45 warnings in 10.80s ======================== RUN EVERY COMMAND 1 pytest tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_multichar_split ============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_unicode_multichar_split [gw0] [100%] FAILED tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_unicode_multichar_split =================================== FAILURES =================================== ______________ test_text_to_word_sequence_unicode_multichar_split ______________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/bin/python def test_text_to_word_sequence_unicode_multichar_split(): text = u'ali!stopveli?stopkırkstopdokuzstopelli' > assert text_to_word_sequence(text, split='stop') == [u'ali', u'veli', u'kırk', u'dokuz', u'elli'] tests/keras/preprocessing/text_test.py:88: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ text = 'ali!stopveli?stopkırkstopdokuzstopelli' filters = '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower = True, split = 'stop' def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" "): """Converts a text to a sequence of words (or tokens). # Arguments text: Input text (string). filters: Sequence of characters to filter out. lower: Whether to convert the input to lowercase. split: Sentence split marker (string). # Returns A list of words (or tokens). """ if lower: text = text.lower() if sys.version_info < (3,) and isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) else: > translate_map = maketrans(filters, split * len(filters)) E ValueError: the first two maketrans arguments must have equal length keras/preprocessing/text.py:44: ValueError =============================== warnings summary =============================== /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/46684df2d5635c359f1cbc5428790f06/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_unicode_multichar_split ======================== 1 failed, 44 warnings in 5.46s ========================
pytest tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_multichar_split pytest tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_unicode_multichar_split
1c9a49781da2101507db23e2014e4e5d16bd2e52
tests/keras/preprocessing/text_test.py
keras-team__keras-45
keras-team/keras
diff --git a/keras/layers/recurrent.py b/keras/layers/recurrent.py index ec9fa871..46eb08cd 100644 --- a/keras/layers/recurrent.py +++ b/keras/layers/recurrent.py @@ -1803,10 +1803,15 @@ class LSTMCell(Layer): inputs_f = inputs inputs_c = inputs inputs_o = inputs - x_i = K.dot(inputs_i, self.kernel_i) + self.bias_i - x_f = K.dot(inputs_f, self.kernel_f) + self.bias_f - x_c = K.dot(inputs_c, self.kernel_c) + self.bias_c - x_o = K.dot(inputs_o, self.kernel_o) + self.bias_o + x_i = K.dot(inputs_i, self.kernel_i) + x_f = K.dot(inputs_f, self.kernel_f) + x_c = K.dot(inputs_c, self.kernel_c) + x_o = K.dot(inputs_o, self.kernel_o) + if self.use_bias: + x_i = K.bias_add(x_i, self.bias_i) + x_f = K.bias_add(x_f, self.bias_f) + x_c = K.bias_add(x_c, self.bias_c) + x_o = K.bias_add(x_o, self.bias_o) if 0 < self.recurrent_dropout < 1.: h_tm1_i = h_tm1 * rec_dp_mask[0]
diff --git a/tests/keras/layers/recurrent_test.py b/tests/keras/layers/recurrent_test.py index 19d318a06..20f0065f3 100644 --- a/tests/keras/layers/recurrent_test.py +++ b/tests/keras/layers/recurrent_test.py @@ -183,6 +183,12 @@ def test_implementation_mode(layer_class): 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) + # Without bias + layer_test(layer_class, + kwargs={'units': units, + 'implementation': mode, + 'use_bias': False}, + input_shape=(num_samples, timesteps, embedding_dim)) @rnn_test
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM] [gw0] [100%] FAILED tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM] =================================== FAILURES =================================== ________________________ test_implementation_mode[LSTM] ________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/bin/python layer_class = <class 'keras.layers.recurrent.LSTM'> @rnn_test def test_implementation_mode(layer_class): for mode in [1, 2]: # Without dropout layer_test(layer_class, kwargs={'units': units, 'implementation': mode}, input_shape=(num_samples, timesteps, embedding_dim)) # With dropout layer_test(layer_class, kwargs={'units': units, 'implementation': mode, 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) # Without bias layer_test(layer_class, kwargs={'units': units, 'implementation': mode, 'use_bias': False}, > input_shape=(num_samples, timesteps, embedding_dim)) tests/keras/layers/recurrent_test.py:191: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/utils/test_utils.py:85: in layer_test y = layer(x) keras/layers/recurrent.py:483: in __call__ return super(RNN, self).__call__(inputs, **kwargs) keras/engine/topology.py:603: in __call__ output = self.call(inputs, **kwargs) keras/layers/recurrent.py:2004: in call initial_state=initial_state) keras/layers/recurrent.py:590: in call input_length=timesteps) keras/backend/tensorflow_backend.py:2533: in rnn outputs, _ = step_function(inputs[0], initial_states + constants) keras/layers/recurrent.py:581: in step return self.cell.call(inputs, states, **kwargs) keras/layers/recurrent.py:1806: in call x_i = K.dot(inputs_i, self.kernel_i) + self.bias_i /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/ops/math_ops.py:903: in binary_op_wrapper y, dtype_hint=x.dtype.base_dtype, name="y") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1242: in convert_to_tensor_v2 as_ref=False) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1297: in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/constant_op.py:286: in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/constant_op.py:227: in constant allow_broadcast=True) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/constant_op.py:265: in _constant_impl allow_broadcast=allow_broadcast)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ values = None, dtype = None, shape = None, verify_shape = False allow_broadcast = True @tf_export("make_tensor_proto") def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False, allow_broadcast=False): """Create a TensorProto. In TensorFlow 2.0, representing tensors as protos should no longer be a common workflow. That said, this utility function is still useful for generating TF Serving request protos: request = tensorflow_serving.apis.predict_pb2.PredictRequest() request.model_spec.name = "my_model" request.model_spec.signature_name = "serving_default" request.inputs["images"].CopyFrom(tf.make_tensor_proto(X_new)) make_tensor_proto accepts "values" of a python scalar, a python list, a numpy ndarray, or a numpy scalar. If "values" is a python scalar or a python list, make_tensor_proto first convert it to numpy ndarray. If dtype is None, the conversion tries its best to infer the right numpy data type. Otherwise, the resulting numpy array has a compatible data type with the given dtype. In either case above, the numpy ndarray (either the caller provided or the auto converted) must have the compatible type with dtype. make_tensor_proto then converts the numpy array to a tensor proto. If "shape" is None, the resulting tensor proto represents the numpy array precisely. Otherwise, "shape" specifies the tensor's shape and the numpy array can not have more elements than what "shape" specifies. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: Boolean that enables verification of a shape of values. allow_broadcast: Boolean that enables allowing scalars and 1 length vector broadcasting. Cannot be true when verify_shape is true. Returns: A `TensorProto`. Depending on the type, it may contain data in the "tensor_content" attribute, which is not directly useful to Python programs. To access the values you should convert the proto back to a numpy ndarray with `tf.make_ndarray(proto)`. If `values` is a `TensorProto`, it is immediately returned; `dtype` and `shape` are ignored. Raises: TypeError: if unsupported types are provided. ValueError: if arguments have inappropriate values or if verify_shape is True and shape of values is not equals to a shape from the argument. """ if allow_broadcast and verify_shape: raise ValueError("allow_broadcast and verify_shape are not both allowed.") if isinstance(values, tensor_pb2.TensorProto): return values if dtype: dtype = dtypes.as_dtype(dtype) is_quantized = ( dtype in [ dtypes.qint8, dtypes.quint8, dtypes.qint16, dtypes.quint16, dtypes.qint32 ]) if _is_array_like(values): values = np.asarray(values) # We first convert value to a numpy array or scalar. if isinstance(values, (np.ndarray, np.generic)): if dtype and dtype.is_numpy_compatible: nparray = values.astype(dtype.as_numpy_dtype) else: nparray = values else: if values is None: > raise ValueError("None values not supported.") E ValueError: None values not supported. /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:437: ValueError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3626: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:1238: calling reduce_sum_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2353: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:158: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:163: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:172: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:180: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:187: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:711: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:671: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version. Instructions for updating: Call initializer instance with the dtype argument instead of passing it to the constructor WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:949: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:936: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2990: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3626: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:deprecation.py:506 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:1238: calling reduce_sum_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2353: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:158: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:163: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:172: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:180: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:187: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:711: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where WARNING tensorflow:deprecation.py:506 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:671: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version. Instructions for updating: Call initializer instance with the dtype argument instead of passing it to the constructor WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:949: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:936: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:deprecation.py:506 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2990: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. =============================== warnings summary =============================== /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:15 keras/callbacks.py:15 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:15: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: 416 tests with warnings /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/11a30c7184b1d2bc0687492d607ca913/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 7.96s call tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM] (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM] ======================= 1 failed, 472 warnings in 12.25s =======================
pytest tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM]
d368dc870bfd8fdd4ca0ff82bd5b61aa549291c5
tests/keras/layers/recurrent_test.py
keras-team__keras-25
keras-team/keras
diff --git a/keras/applications/imagenet_utils.py b/keras/applications/imagenet_utils.py index cfdd1098..d6a3c23d 100644 --- a/keras/applications/imagenet_utils.py +++ b/keras/applications/imagenet_utils.py @@ -38,6 +38,8 @@ def _preprocess_numpy_input(x, data_format, mode): # Returns Preprocessed Numpy array. """ + x = x.astype(K.floatx()) + if mode == 'tf': x /= 127.5 x -= 1.
diff --git a/tests/keras/applications/imagenet_utils_test.py b/tests/keras/applications/imagenet_utils_test.py index 48316a06d..85674b0b9 100644 --- a/tests/keras/applications/imagenet_utils_test.py +++ b/tests/keras/applications/imagenet_utils_test.py @@ -8,23 +8,35 @@ from keras.layers import Input, Lambda def test_preprocess_input(): - # Test image batch + # Test image batch with float and int image input x = np.random.uniform(0, 255, (2, 10, 10, 3)) + xint = x.astype('int32') assert utils.preprocess_input(x).shape == x.shape + assert utils.preprocess_input(xint).shape == xint.shape out1 = utils.preprocess_input(x, 'channels_last') + out1int = utils.preprocess_input(xint, 'channels_last') out2 = utils.preprocess_input(np.transpose(x, (0, 3, 1, 2)), 'channels_first') + out2int = utils.preprocess_input(np.transpose(xint, (0, 3, 1, 2)), + 'channels_first') assert_allclose(out1, out2.transpose(0, 2, 3, 1)) + assert_allclose(out1int, out2int.transpose(0, 2, 3, 1)) # Test single image x = np.random.uniform(0, 255, (10, 10, 3)) + xint = x.astype('int32') assert utils.preprocess_input(x).shape == x.shape + assert utils.preprocess_input(xint).shape == xint.shape out1 = utils.preprocess_input(x, 'channels_last') + out1int = utils.preprocess_input(xint, 'channels_last') out2 = utils.preprocess_input(np.transpose(x, (2, 0, 1)), 'channels_first') + out2int = utils.preprocess_input(np.transpose(xint, (2, 0, 1)), + 'channels_first') assert_allclose(out1, out2.transpose(1, 2, 0)) + assert_allclose(out1int, out2int.transpose(1, 2, 0)) def test_preprocess_input_symbolic():
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/applications/imagenet_utils_test.py::test_preprocess_input [gw1] [100%] FAILED tests/keras/applications/imagenet_utils_test.py::test_preprocess_input =================================== FAILURES =================================== ____________________________ test_preprocess_input _____________________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/bin/python def test_preprocess_input(): # Test image batch with float and int image input x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype('int32') assert utils.preprocess_input(x).shape == x.shape > assert utils.preprocess_input(xint).shape == xint.shape tests/keras/applications/imagenet_utils_test.py:15: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/applications/imagenet_utils.py:178: in preprocess_input return _preprocess_numpy_input(x, data_format=data_format, mode=mode) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ x = array([[[[105, 161, 152], [237, 143, 89], [204, 181, 117], [118, 146, 251], [ 18,... [229, 179, 50], [225, 73, 162], [204, 54, 233], [235, 250, 129]]]], dtype=int32) data_format = 'channels_last', mode = 'caffe' def _preprocess_numpy_input(x, data_format, mode): """Preprocesses a Numpy array encoding a batch of images. # Arguments x: Input array, 3D or 4D. data_format: Data format of the image array. mode: One of "caffe", "tf" or "torch". - caffe: will convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling. - tf: will scale pixels between -1 and 1, sample-wise. - torch: will scale pixels between 0 and 1 and then will normalize each channel with respect to the ImageNet dataset. # Returns Preprocessed Numpy array. """ if mode == 'tf': x /= 127.5 x -= 1. return x if mode == 'torch': x /= 255. mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] else: if data_format == 'channels_first': # 'RGB'->'BGR' if x.ndim == 3: x = x[::-1, ...] else: x = x[:, ::-1, ...] else: # 'RGB'->'BGR' x = x[..., ::-1] mean = [103.939, 116.779, 123.68] std = None # Zero-center by mean pixel if data_format == 'channels_first': if x.ndim == 3: x[0, :, :] -= mean[0] x[1, :, :] -= mean[1] x[2, :, :] -= mean[2] if std is not None: x[0, :, :] /= std[0] x[1, :, :] /= std[1] x[2, :, :] /= std[2] else: x[:, 0, :, :] -= mean[0] x[:, 1, :, :] -= mean[1] x[:, 2, :, :] -= mean[2] if std is not None: x[:, 0, :, :] /= std[0] x[:, 1, :, :] /= std[1] x[:, 2, :, :] /= std[2] else: > x[..., 0] -= mean[0] E numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'subtract' output from dtype('float64') to dtype('int32') with casting rule 'same_kind' keras/applications/imagenet_utils.py:82: UFuncTypeError =============================== warnings summary =============================== /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class ObjectIdentityDictionary(collections.MutableMapping): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/applications/imagenet_utils_test.py::test_preprocess_input ======================== 1 failed, 88 warnings in 6.42s ========================
pytest tests/keras/applications/imagenet_utils_test.py::test_preprocess_input
b470a595f7278acf5e7e47521edf25d3c4f479f1
tests/keras/applications/imagenet_utils_test.py
keras-team__keras-6
keras-team/keras
diff --git a/keras/engine/training_utils.py b/keras/engine/training_utils.py index 68f14ac0..e8116397 100644 --- a/keras/engine/training_utils.py +++ b/keras/engine/training_utils.py @@ -410,7 +410,7 @@ def weighted_masked_objective(fn): score_array *= mask # the loss per batch should be proportional # to the number of unmasked samples. - score_array /= K.mean(mask) + score_array /= K.mean(mask) + K.epsilon() # apply sample weighting if weights is not None:
diff --git a/tests/test_loss_masking.py b/tests/test_loss_masking.py index 45b23b1fb..323443997 100644 --- a/tests/test_loss_masking.py +++ b/tests/test_loss_masking.py @@ -8,20 +8,32 @@ from keras import losses from keras import backend as K +def create_masking_model(): + model = Sequential() + model.add(Masking(mask_value=0, input_shape=(None, 1))) + model.add(TimeDistributed(Dense(1, kernel_initializer='one'))) + model.compile(loss='mse', optimizer='sgd') + return model + + def test_masking(): np.random.seed(1337) x = np.array([[[1], [1]], [[0], [0]]]) - model = Sequential() - model.add(Masking(mask_value=0, input_shape=(2, 1))) - model.add(TimeDistributed(Dense(1, kernel_initializer='one'))) - model.compile(loss='mse', optimizer='sgd') + model = create_masking_model() y = np.array([[[1], [1]], [[1], [1]]]) loss = model.train_on_batch(x, y) assert loss == 0 +def test_masking_is_all_zeros(): + x = y = np.array([[[0], [0]]]) + model = create_masking_model() + loss = model.train_on_batch(x, y) + assert loss == 0 + + def test_loss_masking(): weighted_loss = weighted_masked_objective(losses.get('mae')) shape = (3, 4, 2)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/test_loss_masking.py::test_masking_is_all_zeros [gw0] [100%] FAILED tests/test_loss_masking.py::test_masking_is_all_zeros =================================== FAILURES =================================== __________________________ test_masking_is_all_zeros ___________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_masking_is_all_zeros(): x = y = np.array([[[0], [0]]]) model = create_masking_model() loss = model.train_on_batch(x, y) > assert loss == 0 E assert nan == 0 E +nan E -0 tests/test_loss_masking.py:34: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:997: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:984: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2921: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. 2023-07-15 04:08:43.367544: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 04:08:43.404383: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 04:08:43.411499: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x5575f7b60220 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 04:08:43.411549: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 04:08:43.412904: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 04:08:43.412925: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 04:08:43.412945: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (8cd2fa7be075): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:997: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:984: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2921: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 1.38s call tests/test_loss_masking.py::test_masking_is_all_zeros (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/test_loss_masking.py::test_masking_is_all_zeros - assert nan == 0 ======================== 1 failed, 4 warnings in 16.35s ======================== Using TensorFlow backend.
pytest tests/test_loss_masking.py::test_masking_is_all_zeros
88af7d0c97497b5c3a198ee9416b2accfbc72c36
tests/test_loss_masking.py
keras-team__keras-37
keras-team/keras
diff --git a/keras/layers/recurrent.py b/keras/layers/recurrent.py index f31286db..81c367f9 100644 --- a/keras/layers/recurrent.py +++ b/keras/layers/recurrent.py @@ -518,12 +518,14 @@ class RNN(Layer): self._num_constants = len(constants) additional_specs += self.constants_spec # at this point additional_inputs cannot be empty - is_keras_tensor = hasattr(additional_inputs[0], '_keras_history') + is_keras_tensor = K.is_keras_tensor(additional_inputs[0]) for tensor in additional_inputs: - if hasattr(tensor, '_keras_history') != is_keras_tensor: + if K.is_keras_tensor(tensor) != is_keras_tensor: raise ValueError('The initial state or constants of an RNN' ' layer cannot be specified with a mix of' - ' Keras tensors and non-Keras tensors') + ' Keras tensors and non-Keras tensors' + ' (a "Keras tensor" is a tensor that was' + ' returned by a Keras layer, or by `Input`)') if is_keras_tensor: # Compute the full input spec, including state and constants diff --git a/keras/layers/wrappers.py b/keras/layers/wrappers.py index 7febff35..a5eed289 100644 --- a/keras/layers/wrappers.py +++ b/keras/layers/wrappers.py @@ -275,6 +275,7 @@ class Bidirectional(Wrapper): self.supports_masking = True self._trainable = True super(Bidirectional, self).__init__(layer, **kwargs) + self.input_spec = layer.input_spec @property def trainable(self): @@ -313,6 +314,60 @@ class Bidirectional(Wrapper): return [output_shape] + state_shape + copy.copy(state_shape) return output_shape + def __call__(self, inputs, initial_state=None, **kwargs): + if isinstance(inputs, list): + if len(inputs) > 1: + initial_state = inputs[1:] + inputs = inputs[0] + + if initial_state is None: + return super(Bidirectional, self).__call__(inputs, **kwargs) + + # Standardize `initial_state` into list + if isinstance(initial_state, tuple): + initial_state = list(initial_state) + elif not isinstance(initial_state, list): + initial_state = [initial_state] + + # Check if `initial_state` can be splitted into half + num_states = len(initial_state) + if num_states % 2 > 0: + raise ValueError( + 'When passing `initial_state` to a Bidirectional RNN, the state ' + 'should be a list containing the states of the underlying RNNs. ' + 'Found: ' + str(initial_state)) + + # Applies the same workaround as in `RNN.__call__`, without handling constants + kwargs['initial_state'] = initial_state + additional_inputs = initial_state + additional_specs = [InputSpec(shape=K.int_shape(state)) + for state in initial_state] + self.forward_layer.state_spec = additional_specs[:num_states // 2] + self.backward_layer.state_spec = additional_specs[num_states // 2:] + + is_keras_tensor = K.is_keras_tensor(additional_inputs[0]) + for tensor in additional_inputs: + if K.is_keras_tensor(tensor) != is_keras_tensor: + raise ValueError('The initial state of a Bidirectional' + ' layer cannot be specified with a mix of' + ' Keras tensors and non-Keras tensors' + ' (a "Keras tensor" is a tensor that was' + ' returned by a Keras layer, or by `Input`)') + + if is_keras_tensor: + # Compute the full input spec, including state + full_input = [inputs] + additional_inputs + full_input_spec = self.input_spec + additional_specs + + # Perform the call with temporarily replaced input_spec + original_input_spec = self.input_spec + self.input_spec = full_input_spec + output = super(Bidirectional, self).__call__(full_input, **kwargs) + self.input_spec = original_input_spec + return output + else: + return super(Bidirectional, self).__call__(inputs, **kwargs) + def call(self, inputs, training=None, mask=None, initial_state=None): kwargs = {} if has_arg(self.layer.call, 'training'): @@ -321,11 +376,6 @@ class Bidirectional(Wrapper): kwargs['mask'] = mask if initial_state is not None and has_arg(self.layer.call, 'initial_state'): - if not isinstance(initial_state, list): - raise ValueError( - 'When passing `initial_state` to a Bidirectional RNN, the state ' - 'should be a list containing the states of the underlying RNNs. ' - 'Found: ' + str(initial_state)) forward_state = initial_state[:len(initial_state) // 2] backward_state = initial_state[len(initial_state) // 2:] y = self.forward_layer.call(inputs, initial_state=forward_state, **kwargs)
diff --git a/tests/keras/layers/wrappers_test.py b/tests/keras/layers/wrappers_test.py index 65272d1af..c471a49ed 100644 --- a/tests/keras/layers/wrappers_test.py +++ b/tests/keras/layers/wrappers_test.py @@ -325,19 +325,22 @@ def test_Bidirectional_state_reuse(): timesteps = 3 units = 3 - inputs = Input((timesteps, dim)) + input1 = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True)) - outputs = layer(inputs) - output, state = outputs[0], outputs[1:] + state = layer(input1)[1:] # test passing invalid initial_state: passing a tensor + input2 = Input((timesteps, dim)) with pytest.raises(ValueError): - output = wrappers.Bidirectional(rnn(units))(output, initial_state=state[0]) + output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state[0]) # test valid usage: passing a list - output = wrappers.Bidirectional(rnn(units))(output, initial_state=state) - model = Model(inputs, output) - inputs = np.random.rand(samples, timesteps, dim) + output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state) + model = Model([input1, input2], output) + assert len(model.layers) == 4 + assert isinstance(model.layers[-1].input, list) + inputs = [np.random.rand(samples, timesteps, dim), + np.random.rand(samples, timesteps, dim)] outputs = model.predict(inputs)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse [gw0] [100%] FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse =================================== FAILURES =================================== ________________________ test_Bidirectional_state_reuse ________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/bin/python @keras_test def test_Bidirectional_state_reuse(): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 input1 = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True)) state = layer(input1)[1:] # test passing invalid initial_state: passing a tensor input2 = Input((timesteps, dim)) with pytest.raises(ValueError): output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state[0]) # test valid usage: passing a list output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state) model = Model([input1, input2], output) > assert len(model.layers) == 4 E assert 2 == 4 E +2 E -4 tests/keras/layers/wrappers_test.py:340: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. =============================== warnings summary =============================== /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/a5eabc0de5ef7a4304b455cf663ce107/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.77s call tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse - ... ======================== 1 failed, 45 warnings in 7.47s ========================
pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse
81f6b3aa5b2b6215a533180e848a3b4dff851d03
tests/keras/layers/wrappers_test.py
keras-team__keras-40
keras-team/keras
diff --git a/keras/layers/recurrent.py b/keras/layers/recurrent.py index a94d0623..4b371ff2 100644 --- a/keras/layers/recurrent.py +++ b/keras/layers/recurrent.py @@ -395,9 +395,10 @@ class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): - output_dim = self.cell.state_size[0] + state_size = self.cell.state_size else: - output_dim = self.cell.state_size + state_size = [self.cell.state_size] + output_dim = state_size[0] if self.return_sequences: output_shape = (input_shape[0], input_shape[1], output_dim) @@ -405,7 +406,7 @@ class RNN(Layer): output_shape = (input_shape[0], output_dim) if self.return_state: - state_shape = [(input_shape[0], output_dim) for _ in self.states] + state_shape = [(input_shape[0], dim) for dim in state_size] return [output_shape] + state_shape else: return output_shape
diff --git a/tests/keras/layers/recurrent_test.py b/tests/keras/layers/recurrent_test.py index 074219c16..dd784c234 100644 --- a/tests/keras/layers/recurrent_test.py +++ b/tests/keras/layers/recurrent_test.py @@ -596,6 +596,20 @@ def test_stacked_rnn_attributes(): assert layer.get_losses_for(x) == [y] +@keras_test +def test_stacked_rnn_compute_output_shape(): + cells = [recurrent.LSTMCell(3), + recurrent.LSTMCell(6)] + layer = recurrent.RNN(cells, return_state=True, return_sequences=True) + output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) + expected_output_shape = [(None, timesteps, 6), + (None, 6), + (None, 6), + (None, 3), + (None, 3)] + assert output_shape == expected_output_shape + + @rnn_test def test_batch_size_equal_one(layer_class): inputs = Input(batch_shape=(1, timesteps, embedding_dim))
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape [gw0] [100%] FAILED tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape =================================== FAILURES =================================== ____________________ test_stacked_rnn_compute_output_shape _____________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python @keras_test def test_stacked_rnn_compute_output_shape(): cells = [recurrent.LSTMCell(3), recurrent.LSTMCell(6)] layer = recurrent.RNN(cells, return_state=True, return_sequences=True) output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) expected_output_shape = [(None, timesteps, 6), (None, 6), (None, 6), (None, 3), (None, 3)] > assert output_shape == expected_output_shape E assert [(None, 5, 6)...6), (None, 6)] == [(None, 5, 6)...3), (None, 3)] E At index 3 diff: (None, 6) != (None, 3) E Full diff: E - [(None, 5, 6), (None, 6), (None, 6), (None, 3), (None, 3)] E ? ^ ^ E + [(None, 5, 6), (None, 6), (None, 6), (None, 6), (None, 6)] E ? ^ ^ tests/keras/layers/recurrent_test.py:610: AssertionError =============================== warnings summary =============================== /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:15 keras/callbacks.py:15 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:15: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape ======================== 1 failed, 55 warnings in 6.04s ========================
pytest tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape
871007dbb0e6211459b9d16244cc3c9683459df7
tests/keras/layers/recurrent_test.py
keras-team__keras-31
keras-team/keras
diff --git a/keras/backend/tensorflow_backend.py b/keras/backend/tensorflow_backend.py index f145d43d..0e313bc5 100644 --- a/keras/backend/tensorflow_backend.py +++ b/keras/backend/tensorflow_backend.py @@ -3942,8 +3942,8 @@ def ctc_batch_cost(y_true, y_pred, input_length, label_length): Tensor with shape (samples,1) containing the CTC loss of each element. """ - label_length = tf.to_int32(tf.squeeze(label_length)) - input_length = tf.to_int32(tf.squeeze(input_length)) + label_length = tf.to_int32(tf.squeeze(label_length, axis=-1)) + input_length = tf.to_int32(tf.squeeze(input_length, axis=-1)) sparse_labels = tf.to_int32(ctc_label_dense_to_sparse(y_true, label_length)) y_pred = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + epsilon())
diff --git a/tests/keras/backend/backend_test.py b/tests/keras/backend/backend_test.py index 25003d442..037628cff 100644 --- a/tests/keras/backend/backend_test.py +++ b/tests/keras/backend/backend_test.py @@ -1475,6 +1475,32 @@ class TestBackend(object): res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens)) assert_allclose(res[0, :] if K.backend() == 'theano' else res[:, 0], ref, atol=1e-05) + # test when batch_size = 1, that is, one sample only + # get only first sample from above test case + if K.backend() == 'theano': + ref = [1.73308] + else: + ref = [3.34211] + + input_lens = np.expand_dims(np.asarray([5]), 1) + label_lens = np.expand_dims(np.asarray([5]), 1) + + labels = np.asarray([[0, 1, 2, 1, 0]]) + inputs = np.asarray( + [[[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553], + [0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436], + [0.0357786, 0.633813, 0.321418, 0.00249248, 0.00272882, 0.0037688], + [0.0663296, 0.643849, 0.280111, 0.00283995, 0.0035545, 0.00331533], + [0.458235, 0.396634, 0.123377, 0.00648837, 0.00903441, 0.00623107]]], + dtype=np.float32) + + k_labels = K.variable(labels, dtype="int32") + k_inputs = K.variable(inputs, dtype="float32") + k_input_lens = K.variable(input_lens, dtype="int32") + k_label_lens = K.variable(label_lens, dtype="int32") + res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens)) + assert_allclose(res[0, :] if K.backend() == 'theano' else res[:, 0], ref, atol=1e-05) + '''only tensorflow tested, need special handle''' def test_ctc_decode_greedy(self):
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/backend/backend_test.py::TestBackend::test_ctc [gw0] [100%] FAILED tests/keras/backend/backend_test.py::TestBackend::test_ctc =================================== FAILURES =================================== _____________________________ TestBackend.test_ctc _____________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/bin/python self = <backend_test.TestBackend object at 0x7ffbaefb96a0> @pytest.mark.skipif(K.backend() == 'cntk', reason='Not supported.') def test_ctc(self): if K.backend() == 'theano': ref = [1.73308, 3.81351] else: ref = [3.34211, 5.42262] # simplified version of TensorFlow's test label_lens = np.expand_dims(np.asarray([5, 4]), 1) input_lens = np.expand_dims(np.asarray([5, 5]), 1) # number of timesteps # dimensions are batch x time x categories labels = np.asarray([[0, 1, 2, 1, 0], [0, 1, 1, 0, -1]]) inputs = np.asarray( [[[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553], [0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436], [0.0357786, 0.633813, 0.321418, 0.00249248, 0.00272882, 0.0037688], [0.0663296, 0.643849, 0.280111, 0.00283995, 0.0035545, 0.00331533], [0.458235, 0.396634, 0.123377, 0.00648837, 0.00903441, 0.00623107]], [[0.30176, 0.28562, 0.0831517, 0.0862751, 0.0816851, 0.161508], [0.24082, 0.397533, 0.0557226, 0.0546814, 0.0557528, 0.19549], [0.230246, 0.450868, 0.0389607, 0.038309, 0.0391602, 0.202456], [0.280884, 0.429522, 0.0326593, 0.0339046, 0.0326856, 0.190345], [0.423286, 0.315517, 0.0338439, 0.0393744, 0.0339315, 0.154046]]], dtype=np.float32) k_labels = K.variable(labels, dtype="int32") k_inputs = K.variable(inputs, dtype="float32") k_input_lens = K.variable(input_lens, dtype="int32") k_label_lens = K.variable(label_lens, dtype="int32") res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens)) assert_allclose(res[0, :] if K.backend() == 'theano' else res[:, 0], ref, atol=1e-05) # test when batch_size = 1, that is, one sample only # get only first sample from above test case if K.backend() == 'theano': ref = [1.73308] else: ref = [3.34211] input_lens = np.expand_dims(np.asarray([5]), 1) label_lens = np.expand_dims(np.asarray([5]), 1) labels = np.asarray([[0, 1, 2, 1, 0]]) inputs = np.asarray( [[[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553], [0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436], [0.0357786, 0.633813, 0.321418, 0.00249248, 0.00272882, 0.0037688], [0.0663296, 0.643849, 0.280111, 0.00283995, 0.0035545, 0.00331533], [0.458235, 0.396634, 0.123377, 0.00648837, 0.00903441, 0.00623107]]], dtype=np.float32) k_labels = K.variable(labels, dtype="int32") k_inputs = K.variable(inputs, dtype="float32") k_input_lens = K.variable(input_lens, dtype="int32") k_label_lens = K.variable(label_lens, dtype="int32") > res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens)) tests/keras/backend/backend_test.py:1501: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/backend/tensorflow_backend.py:3947: in ctc_batch_cost sparse_labels = tf.to_int32(ctc_label_dense_to_sparse(y_true, label_length)) keras/backend/tensorflow_backend.py:3911: in ctc_label_dense_to_sparse initializer=init, parallel_iterations=1) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/ops/functional_ops.py:651: in scan n = (tensor_shape.dimension_value(elems_flat[0].shape[0]) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = TensorShape([]), key = 0 def __getitem__(self, key): """Returns the value of a dimension or a shape, depending on the key. Args: key: If `key` is an integer, returns the dimension at that index; otherwise if `key` is a slice, returns a TensorShape whose dimensions are those selected by the slice from `self`. Returns: An integer if `key` is an integer, or a `TensorShape` if `key` is a slice. Raises: ValueError: If `key` is a slice and `self` is completely unknown and the step is set. """ if self._dims is not None: if isinstance(key, slice): return TensorShape(self._dims[key]) else: if self._v2_behavior: return self._dims[key].value else: > return self._dims[key] E IndexError: list index out of range /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/tensor_shape.py:788: IndexError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3945: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3925: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. 2023-07-15 06:17:01.142273: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:17:01.155223: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:17:01.155501: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55da94fc7260 executing computations on platform Host. Devices: 2023-07-15 06:17:01.155542: I tensorflow/compiler/xla/service/service.cc:158] StreamExecutor device (0): <undefined>, <undefined> ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING tensorflow:deprecation.py:323 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3945: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. WARNING tensorflow:deprecation.py:323 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3925: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. =============================== warnings summary =============================== /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable tests/keras/backend/backend_test.py:20 tests/keras/backend/backend_test.py:20 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:20: UserWarning: Could not import the CNTK backend warnings.warn('Could not import the CNTK backend') tests/keras/backend/backend_test.py:34 tests/keras/backend/backend_test.py:34 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:34: UserWarning: Could not import the Theano backend warnings.warn('Could not import the Theano backend') /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/7ba78bf48f247a0c342bdbb3158dc533/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.69s call tests/keras/backend/backend_test.py::TestBackend::test_ctc (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/backend/backend_test.py::TestBackend::test_ctc - IndexErro... ======================= 1 failed, 49 warnings in 15.43s ========================
pytest tests/keras/backend/backend_test.py::TestBackend::test_ctc
ced81968b0e9d8b1389e6580721ac60d9cf3ca60
tests/keras/backend/backend_test.py
keras-team__keras-2
keras-team/keras
diff --git a/keras/backend/numpy_backend.py b/keras/backend/numpy_backend.py index fe23567a..1e061955 100644 --- a/keras/backend/numpy_backend.py +++ b/keras/backend/numpy_backend.py @@ -316,6 +316,12 @@ def l2_normalize(x, axis=-1): return x / np.sqrt(y) +def in_top_k(predictions, targets, k): + top_k = np.argsort(-predictions)[:, :k] + targets = targets.reshape(-1, 1) + return np.any(targets == top_k, axis=-1) + + def binary_crossentropy(target, output, from_logits=False): if not from_logits: output = np.clip(output, 1e-7, 1 - 1e-7)
diff --git a/tests/keras/backend/backend_test.py b/tests/keras/backend/backend_test.py index 62e0a4f9e..da433ca34 100644 --- a/tests/keras/backend/backend_test.py +++ b/tests/keras/backend/backend_test.py @@ -1156,6 +1156,7 @@ class TestBackend(object): check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=-1) check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=1) + @pytest.mark.skipif(K.backend() == 'cntk', reason='Bug in CNTK') def test_in_top_k(self): batch_size = 20 num_classes = 10 @@ -1166,10 +1167,10 @@ class TestBackend(object): # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. - for k in range(num_classes + 1): + for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) - for b in [KTH, KTF]] + for b in WITH_NP] assert_list_pairwise(z_list) # Identical prediction test case: @@ -1184,7 +1185,7 @@ class TestBackend(object): for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) - for b in [KTH, KTF]] + for b in WITH_NP] assert_list_pairwise(z_list) @pytest.mark.parametrize('op,input_shape,kernel_shape,padding,data_format', [
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/backend/backend_test.py::TestBackend::test_in_top_k [gw0] [100%] FAILED tests/keras/backend/backend_test.py::TestBackend::test_in_top_k =================================== FAILURES =================================== __________________________ TestBackend.test_in_top_k ___________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python self = <backend_test.TestBackend object at 0x7f34acce1da0> @pytest.mark.skipif(K.backend() == 'cntk', reason='Bug in CNTK') def test_in_top_k(self): batch_size = 20 num_classes = 10 # Random prediction test case predictions = np.random.random((batch_size, num_classes)).astype('float32') targets = np.random.randint(num_classes, size=batch_size, dtype='int32') # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) > for b in WITH_NP] tests/keras/backend/backend_test.py:1173: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .0 = <list_iterator object at 0x7f34a63670b8> z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) > for b in WITH_NP] E AttributeError: module 'keras.backend.numpy_backend' has no attribute 'in_top_k' tests/keras/backend/backend_test.py:1173: AttributeError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:178: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:185: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:191: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. 2023-07-15 03:39:11.498396: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 03:39:11.582183: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 03:39:11.582381: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x557a5e182950 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 03:39:11.582395: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 03:39:11.583939: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 03:39:11.583958: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 03:39:11.583974: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (8cd2fa7be075): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:195: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:204: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:211: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:178: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:185: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:191: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:195: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:204: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:211: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:99: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:104: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:99: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:104: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. =============================== warnings summary =============================== tests/keras/backend/backend_test.py:17 tests/keras/backend/backend_test.py:17 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:17: UserWarning: Could not import the CNTK backend warnings.warn('Could not import the CNTK backend') tests/keras/backend/backend_test.py:29 tests/keras/backend/backend_test.py:29 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:29: UserWarning: Could not import the Theano backend warnings.warn('Could not import the Theano backend') /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.24s call tests/keras/backend/backend_test.py::TestBackend::test_in_top_k 0.01s teardown tests/keras/backend/backend_test.py::TestBackend::test_in_top_k (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/backend/backend_test.py::TestBackend::test_in_top_k - Attr... ======================== 1 failed, 7 warnings in 31.26s ======================== Using TensorFlow backend.
pytest tests/keras/backend/backend_test.py::TestBackend::test_in_top_k
2f55055a9f053b35fa721d3eb75dd07ea5a5f1e3
tests/keras/backend/backend_test.py
keras-team__keras-21
keras-team/keras
diff --git a/keras/callbacks.py b/keras/callbacks.py index 067169f3..04826921 100644 --- a/keras/callbacks.py +++ b/keras/callbacks.py @@ -477,6 +477,10 @@ class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. + restore_best_weights: whether to restore model weights from + the epoch with the best value of the monitored quantity. + If False, the model weights obtained at the last step of + training are used. """ def __init__(self, @@ -485,7 +489,8 @@ class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', - baseline=None): + baseline=None, + restore_best_weights=False): super(EarlyStopping, self).__init__() self.monitor = monitor @@ -495,6 +500,8 @@ class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 + self.restore_best_weights = restore_best_weights + self.best_weights = None if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, ' @@ -538,11 +545,17 @@ class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 + if self.restore_best_weights: + self.best_weights = self.model.get_weights() else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_training = True + if self.restore_best_weights: + if self.verbose > 0: + print("Restoring model weights from the end of the best epoch") + self.model.set_weights(self.best_weights) def on_train_end(self, logs=None): if self.stopped_epoch > 0 and self.verbose > 0:
diff --git a/tests/keras/test_callbacks.py b/tests/keras/test_callbacks.py index 1eaba26fc..b3c98abc4 100644 --- a/tests/keras/test_callbacks.py +++ b/tests/keras/test_callbacks.py @@ -267,6 +267,12 @@ def test_EarlyStopping_patience(): def __init__(self): self.stop_training = False + def get_weights(self): + return [] + + def set_weights(self, weights): + pass + early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) early_stop.model = DummyModel() @@ -292,6 +298,12 @@ def test_EarlyStopping_baseline(): def __init__(self): self.stop_training = False + def get_weights(self): + return [] + + def set_weights(self, weights): + pass + def baseline_tester(acc_levels): early_stop = callbacks.EarlyStopping(monitor='val_acc', baseline=0.75, patience=2) early_stop.model = DummyModel() @@ -315,6 +327,84 @@ def test_EarlyStopping_baseline(): assert baseline_not_met == 2 +@keras_test +def test_EarlyStopping_final_weights(): + class DummyModel(object): + def __init__(self): + self.stop_training = False + self.weights = -1 + + def get_weights(self): + return self.weights + + def set_weights(self, weights): + self.weights = weights + + def set_weight_to_epoch(self, epoch): + self.weights = epoch + + early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) + early_stop.model = DummyModel() + + losses = [0.2, 0.15, 0.1, 0.11, 0.12] + + epochs_trained = 0 + early_stop.on_train_begin() + + for epoch in range(len(losses)): + epochs_trained += 1 + early_stop.model.set_weight_to_epoch(epoch=epoch) + early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) + + if early_stop.model.stop_training: + break + + # The best configuration is in the epoch 2 (loss = 0.1000), + # so with patience=2 we need to end up at epoch 4 + assert early_stop.model.get_weights() == 4 + + +@keras_test +def test_EarlyStopping_final_weights_when_restoring_model_weights(): + class DummyModel(object): + def __init__(self): + self.stop_training = False + self.weights = -1 + + def get_weights(self): + return self.weights + + def set_weights(self, weights): + self.weights = weights + + def set_weight_to_epoch(self, epoch): + self.weights = epoch + + early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2, + restore_best_weights=True) + early_stop.model = DummyModel() + + losses = [0.2, 0.15, 0.1, 0.11, 0.12] + + # The best configuration is in the epoch 2 (loss = 0.1000). + + epochs_trained = 0 + early_stop.on_train_begin() + + for epoch in range(len(losses)): + epochs_trained += 1 + early_stop.model.set_weight_to_epoch(epoch=epoch) + early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) + + if early_stop.model.stop_training: + break + + # The best configuration is in epoch 2 (loss = 0.1000), + # and while patience = 2, we're restoring the best weights, + # so we end up at the epoch with the best weights, i.e. epoch 2 + assert early_stop.model.get_weights() == 2 + + @keras_test def test_LearningRateScheduler(): np.random.seed(1337)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [0] / gw1 [0] scheduling tests via LoadScheduling ==================================== ERRORS ==================================== ________________ ERROR collecting tests/keras/test_callbacks.py ________________ tests/keras/test_callbacks.py:9: in <module> from keras import optimizers keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. ________________ ERROR collecting tests/keras/test_callbacks.py ________________ tests/keras/test_callbacks.py:9: in <module> from keras import optimizers keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. =============================== warnings summary =============================== /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ ERROR tests/keras/test_callbacks.py - AttributeError: module 'keras_applicati... ERROR tests/keras/test_callbacks.py - AttributeError: module 'keras_applicati... ======================== 56 warnings, 2 errors in 5.19s ========================
pytest tests/keras/test_callbacks.py::test_EarlyStopping_final_weights_when_restoring_model_weights
c7b7328cc99fd5d7c298e57c6020043451d89a61
tests/keras/test_callbacks.py
keras-team__keras-3
keras-team/keras
diff --git a/keras/models.py b/keras/models.py index a03b09ab..03c487dd 100644 --- a/keras/models.py +++ b/keras/models.py @@ -137,9 +137,12 @@ def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) - output_masks = to_list( - layer.compute_mask(computed_tensor, - computed_mask)) + if layer.supports_masking: + output_masks = to_list( + layer.compute_mask(computed_tensor, + computed_mask)) + else: + output_masks = [None] * len(output_tensors) computed_tensors = [computed_tensor] computed_masks = [computed_mask] else: @@ -150,9 +153,12 @@ def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) - output_masks = to_list( - layer.compute_mask(computed_tensors, - computed_masks)) + if layer.supports_masking: + output_masks = to_list( + layer.compute_mask(computed_tensors, + computed_masks)) + else: + output_masks = [None] * len(output_tensors) # Update tensor_map. for x, y, mask in zip(reference_output_tensors, output_tensors,
diff --git a/tests/keras/test_sequential_model.py b/tests/keras/test_sequential_model.py index d848734f6..13160734c 100644 --- a/tests/keras/test_sequential_model.py +++ b/tests/keras/test_sequential_model.py @@ -339,6 +339,33 @@ def test_clone_functional_model(): new_model.train_on_batch(None, val_out) +def test_clone_functional_model_with_multi_outputs(): + input_layer = keras.Input(shape=(4,)) + + # Layer with single input and multiple outputs + layer1 = keras.layers.Lambda(lambda x: [x + 1, x], + lambda shapes: [shapes, shapes]) + x_a, x_b = layer1(input_layer) + + class SwapLayer(keras.layers.Layer): + def call(self, inputs, **kwargs): + return [inputs[1], inputs[0]] + + def compute_output_shape(self, input_shape): + return [input_shape[1], input_shape[0]] + + # Layer with multiple inputs and outputs + x_a, x_b = SwapLayer()([x_a, x_b]) + model = keras.Model(inputs=[input_layer], outputs=[x_a, x_b]) + new_model = keras.models.clone_model(model) + + x_test = np.random.random((10, 4)) + pred_a, pred_b = model.predict(x_test) + pred_new_a, pred_new_b = new_model.predict(x_test) + assert(pred_a.all() == pred_new_a.all()) + assert(pred_b.all() == pred_new_b.all()) + + def test_clone_sequential_model(): val_a = np.random.random((10, 4)) val_out = np.random.random((10, 4))
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs [gw0] [100%] FAILED tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs =================================== FAILURES =================================== ________________ test_clone_functional_model_with_multi_outputs ________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_clone_functional_model_with_multi_outputs(): input_layer = keras.Input(shape=(4,)) # Layer with single input and multiple outputs layer1 = keras.layers.Lambda(lambda x: [x + 1, x], lambda shapes: [shapes, shapes]) x_a, x_b = layer1(input_layer) class SwapLayer(keras.layers.Layer): def call(self, inputs, **kwargs): return [inputs[1], inputs[0]] def compute_output_shape(self, input_shape): return [input_shape[1], input_shape[0]] # Layer with multiple inputs and outputs x_a, x_b = SwapLayer()([x_a, x_b]) model = keras.Model(inputs=[input_layer], outputs=[x_a, x_b]) > new_model = keras.models.clone_model(model) tests/keras/test_sequential_model.py:360: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/models.py:251: in clone_model return _clone_functional_model(model, input_tensors=input_tensors) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ model = <keras.engine.training.Model object at 0x7f1009887160> input_tensors = [<tf.Tensor 'input_1_1:0' shape=(?, 4) dtype=float32>] def _clone_functional_model(model, input_tensors=None): """Clone a functional `Model` instance. Model cloning is similar to calling a model on new inputs, except that it creates new layers (and thus new weights) instead of sharing the weights of the existing layers. # Arguments model: Instance of `Model`. input_tensors: optional list of input tensors to build the model upon. If not provided, placeholders will be created. # Returns An instance of `Model` reproducing the behavior of the original model, on top of new inputs tensors, using newly instantiated weights. # Raises ValueError: in case of invalid `model` argument value. """ if not isinstance(model, Model): raise ValueError('Expected `model` argument ' 'to be a `Model` instance, got ', model) if isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to be a functional `Model` instance, ' 'got a `Sequential` instance instead:', model) layer_map = {} # Cache for created layers. tensor_map = {} # Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors is None: # Create placeholders to build the model on top of. input_layers = [] input_tensors = [] for layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly created input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original, _cloned in zip(model._input_layers, input_layers): layer_map[_original] = _cloned else: # Make sure that all input tensors come from a Keras layer. # If tensor comes from an input layer: cache the input layer. input_tensors = to_list(input_tensors) _input_tensors = [] for i, x in enumerate(input_tensors): if not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache newly created input layer. original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors for x, y in zip(model.inputs, input_tensors): tensor_map[x] = (y, None) # tensor, mask # Iterated over every node in the reference model, in depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys: nodes = model._nodes_by_depth[depth] for node in nodes: # Recover the corresponding layer. layer = node.outbound_layer # Get or create layer. if layer not in layer_map: # Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer = new_layer else: # Reuse previously cloned layer. layer = layer_map[layer] # Don't call InputLayer multiple times. if isinstance(layer, InputLayer): continue # Gather inputs to call the new layer. reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors # If all previous input tensors are available in tensor_map, # then call node.inbound_layer on them. computed_data = [] # List of tuples (input, mask). for x in reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): # Call layer. if node.arguments: kwargs = node.arguments else: kwargs = {} if len(computed_data) == 1: computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks = [computed_mask] else: computed_tensors = [x[0] for x in computed_data] computed_masks = [x[1] for x in computed_data] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for x, y, mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y, mask) # Check that we did compute the model outputs, # then instantiate a new model from inputs and outputs. output_tensors = [] for x in model.outputs: > assert x in tensor_map, 'Could not compute output ' + str(x) E AssertionError: Could not compute output Tensor("swap_layer_1/Identity:0", shape=(?, 4), dtype=float32) keras/models.py:166: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:528: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:528: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:99: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:99: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.06s call tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs 0.03s teardown tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs ======================== 1 failed, 1 warning in 22.52s ========================= Using TensorFlow backend.
pytest tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs
c0d1709cbae3d05efc6dd224230012bc120be8e5
tests/keras/test_sequential_model.py
keras-team__keras-26
keras-team/keras
diff --git a/keras/backend/tensorflow_backend.py b/keras/backend/tensorflow_backend.py index cd57dfbe..117c72e5 100644 --- a/keras/backend/tensorflow_backend.py +++ b/keras/backend/tensorflow_backend.py @@ -2871,7 +2871,10 @@ def rnn(step_function, inputs, initial_states, tiled_mask_t = tf.tile(mask_t, tf.stack([1, tf.shape(output)[1]])) output = tf.where(tiled_mask_t, output, states[0]) - new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i in range(len(states))] + new_states = [ + tf.where(tf.tile(mask_t, tf.stack([1, tf.shape(new_states[i])[1]])), + new_states[i], states[i]) for i in range(len(states)) + ] output_ta_t = output_ta_t.write(time, output) return (time + 1, output_ta_t) + tuple(new_states) else:
diff --git a/tests/keras/backend/backend_test.py b/tests/keras/backend/backend_test.py index 6cd72e611..2504522be 100644 --- a/tests/keras/backend/backend_test.py +++ b/tests/keras/backend/backend_test.py @@ -599,6 +599,82 @@ class TestBackend(object): assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) assert_allclose(state_list[i - 1], state_list[i], atol=1e-05) + def test_rnn_additional_states(self): + # implement a simple RNN with an additional state + # whose shape is different from that of the output + num_samples = 4 + input_dim = 5 + output_dim = 3 + timesteps = 6 + + _, x = parse_shape_or_val((num_samples, timesteps, input_dim)) + _, h0 = parse_shape_or_val((num_samples, output_dim)) + _, wi = parse_shape_or_val((input_dim, output_dim)) + _, wh = parse_shape_or_val((output_dim, output_dim)) + mask = np.random.randint(2, size=(num_samples, timesteps)) + + x_k = K.variable(x) + h0_k = [K.variable(h0), K.variable(np.concatenate([h0, h0], axis=-1))] + wi_k = K.variable(wi) + wh_k = K.variable(wh) + mask_k = K.variable(mask) + + def rnn_fn(x_k, h_k): + assert len(h_k) == 2 + y_k = K.dot(x_k, wi_k) + K.dot(h_k[0], wh_k) + return y_k, [y_k, K.concatenate([y_k, y_k], axis=-1)] + + # test default setup + last_output_list = [] + outputs_list = [] + state_list = [] + + kwargs_list = [ + {'go_backwards': False, 'mask': None}, + {'go_backwards': False, 'mask': None, 'unroll': True, 'input_length': timesteps}, + {'go_backwards': True, 'mask': None}, + {'go_backwards': True, 'mask': None, 'unroll': True, 'input_length': timesteps}, + {'go_backwards': False, 'mask': mask_k}, + {'go_backwards': False, 'mask': mask_k, 'unroll': True, 'input_length': timesteps}, + ] + + for (i, kwargs) in enumerate(kwargs_list): + last_y1, y1, h1 = reference_operations.rnn(x, [wi, wh, None], h0, **kwargs) + last_y2, y2, h2 = K.rnn(rnn_fn, x_k, h0_k, **kwargs) + + assert len(h2) == 2 + last_y2 = K.eval(last_y2) + y2 = K.eval(y2) + h11 = h1[:, -1] + h12 = np.concatenate([h1[:, -1], h1[:, -1]], axis=-1) + h21 = K.eval(h2[0]) + h22 = K.eval(h2[1]) + + if kwargs['mask'] is not None: + last_y1 = last_y1 * np.expand_dims(mask[:, -1], -1) + last_y2 = last_y2 * np.expand_dims(mask[:, -1], -1) + y1 = y1 * np.expand_dims(mask, -1) + y2 = y2 * np.expand_dims(mask, -1) + h11 = h11 * np.expand_dims(mask[:, -1], -1) + h21 = h21 * np.expand_dims(mask[:, -1], -1) + h12 = h12 * np.expand_dims(mask[:, -1], -1) + h22 = h22 * np.expand_dims(mask[:, -1], -1) + + last_output_list.append(last_y2) + outputs_list.append(y2) + state_list.append((h21, h22)) + + if i % 2 == 0: + assert_allclose(last_y1, last_y2, atol=1e-05) + assert_allclose(y1, y2, atol=1e-05) + assert_allclose(h11, h21, atol=1e-05) + assert_allclose(h12, h22, atol=1e-05) + else: + assert_allclose(last_output_list[i - 1], last_output_list[i], atol=1e-05) + assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) + assert_allclose(state_list[i - 1][0], state_list[i][0], atol=1e-05) + assert_allclose(state_list[i - 1][1], state_list[i][1], atol=1e-05) + def test_rnn_no_states(self): # implement a simple RNN without states input_dim = 8
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states [gw1] [100%] FAILED tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states =================================== FAILURES =================================== ____________________ TestBackend.test_rnn_additional_states ____________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/bin/python graph = <tensorflow.python.framework.ops.Graph object at 0x7fa323ce28d0> node_def = name: "while_2/Select_2" op: "Select" attr { key: "T" value { type: DT_FLOAT } } inputs = [<tf.Tensor 'while_2/Tile:0' shape=(4, 3) dtype=bool>, <tf.Tensor 'while_2/concat:0' shape=(4, 6) dtype=float32>, <tf.Tensor 'while_2/Identity_3:0' shape=(4, 6) dtype=float32>] control_inputs = [] def _create_c_op(graph, node_def, inputs, control_inputs): """Creates a TF_Operation. Args: graph: a `Graph`. node_def: `node_def_pb2.NodeDef` for the operation to create. inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of `Tensor`s (corresponding to sequence inputs, e.g. "int64 * N", "list(int64)"). The length of the list should be equal to the number of inputs specified by this operation's op def. control_inputs: A list of `Operation`s to set as control dependencies. Returns: A wrapped TF_Operation*. """ # pylint: disable=protected-access op_desc = c_api.TF_NewOperation(graph._c_graph, compat.as_str(node_def.op), compat.as_str(node_def.name)) if node_def.device: c_api.TF_SetDevice(op_desc, compat.as_str(node_def.device)) # Add inputs for op_input in inputs: if isinstance(op_input, (list, tuple)): c_api.TF_AddInputList(op_desc, [t._as_tf_output() for t in op_input]) else: c_api.TF_AddInput(op_desc, op_input._as_tf_output()) # Add control inputs for control_input in control_inputs: c_api.TF_AddControlInput(op_desc, control_input._c_op) # pylint: enable=protected-access # Add attrs for name, attr_value in node_def.attr.items(): serialized = attr_value.SerializeToString() # TODO(skyewm): this creates and deletes a new TF_Status for every attr. # It might be worth creating a convenient way to re-use the same status. c_api.TF_SetAttrValueProto(op_desc, compat.as_str(name), serialized) try: > c_op = c_api.TF_FinishOperation(op_desc) E tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimension 1 in both shapes must be equal, but are 6 and 3. Shapes are [4,6] and [4,3]. for 'while_2/Select_2' (op: 'Select') with input shapes: [4,3], [4,6], [4,6]. /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1864: InvalidArgumentError During handling of the above exception, another exception occurred: self = <backend_test.TestBackend object at 0x7fa323ce2ac8> def test_rnn_additional_states(self): # implement a simple RNN with an additional state # whose shape is different from that of the output num_samples = 4 input_dim = 5 output_dim = 3 timesteps = 6 _, x = parse_shape_or_val((num_samples, timesteps, input_dim)) _, h0 = parse_shape_or_val((num_samples, output_dim)) _, wi = parse_shape_or_val((input_dim, output_dim)) _, wh = parse_shape_or_val((output_dim, output_dim)) mask = np.random.randint(2, size=(num_samples, timesteps)) x_k = K.variable(x) h0_k = [K.variable(h0), K.variable(np.concatenate([h0, h0], axis=-1))] wi_k = K.variable(wi) wh_k = K.variable(wh) mask_k = K.variable(mask) def rnn_fn(x_k, h_k): assert len(h_k) == 2 y_k = K.dot(x_k, wi_k) + K.dot(h_k[0], wh_k) return y_k, [y_k, K.concatenate([y_k, y_k], axis=-1)] # test default setup last_output_list = [] outputs_list = [] state_list = [] kwargs_list = [ {'go_backwards': False, 'mask': None}, {'go_backwards': False, 'mask': None, 'unroll': True, 'input_length': timesteps}, {'go_backwards': True, 'mask': None}, {'go_backwards': True, 'mask': None, 'unroll': True, 'input_length': timesteps}, {'go_backwards': False, 'mask': mask_k}, {'go_backwards': False, 'mask': mask_k, 'unroll': True, 'input_length': timesteps}, ] for (i, kwargs) in enumerate(kwargs_list): last_y1, y1, h1 = reference_operations.rnn(x, [wi, wh, None], h0, **kwargs) > last_y2, y2, h2 = K.rnn(rnn_fn, x_k, h0_k, **kwargs) tests/keras/backend/backend_test.py:643: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/backend/tensorflow_backend.py:2906: in rnn swap_memory=True) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/ops/control_flow_ops.py:3501: in while_loop return_same_structure) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/ops/control_flow_ops.py:3012: in BuildLoop pred, body, original_loop_vars, loop_vars, shape_invariants) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/ops/control_flow_ops.py:2937: in _BuildLoop body_result = body(*packed_vars_for_body) keras/backend/tensorflow_backend.py:2874: in _step new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i in range(len(states))] keras/backend/tensorflow_backend.py:2874: in <listcomp> new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i in range(len(states))] /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py:324: in new_func return func(*args, **kwargs) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/dispatch.py:180: in wrapper return target(*args, **kwargs) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py:3270: in where return gen_math_ops.select(condition=condition, x=x, y=y, name=name) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:9226: in select "Select", condition=condition, t=x, e=y, name=name) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:788: in _apply_op_helper op_def=op_def) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py:507: in new_func return func(*args, **kwargs) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:3616: in create_op op_def=op_def) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:2027: in __init__ control_input_ops) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graph = <tensorflow.python.framework.ops.Graph object at 0x7fa323ce28d0> node_def = name: "while_2/Select_2" op: "Select" attr { key: "T" value { type: DT_FLOAT } } inputs = [<tf.Tensor 'while_2/Tile:0' shape=(4, 3) dtype=bool>, <tf.Tensor 'while_2/concat:0' shape=(4, 6) dtype=float32>, <tf.Tensor 'while_2/Identity_3:0' shape=(4, 6) dtype=float32>] control_inputs = [] def _create_c_op(graph, node_def, inputs, control_inputs): """Creates a TF_Operation. Args: graph: a `Graph`. node_def: `node_def_pb2.NodeDef` for the operation to create. inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of `Tensor`s (corresponding to sequence inputs, e.g. "int64 * N", "list(int64)"). The length of the list should be equal to the number of inputs specified by this operation's op def. control_inputs: A list of `Operation`s to set as control dependencies. Returns: A wrapped TF_Operation*. """ # pylint: disable=protected-access op_desc = c_api.TF_NewOperation(graph._c_graph, compat.as_str(node_def.op), compat.as_str(node_def.name)) if node_def.device: c_api.TF_SetDevice(op_desc, compat.as_str(node_def.device)) # Add inputs for op_input in inputs: if isinstance(op_input, (list, tuple)): c_api.TF_AddInputList(op_desc, [t._as_tf_output() for t in op_input]) else: c_api.TF_AddInput(op_desc, op_input._as_tf_output()) # Add control inputs for control_input in control_inputs: c_api.TF_AddControlInput(op_desc, control_input._c_op) # pylint: enable=protected-access # Add attrs for name, attr_value in node_def.attr.items(): serialized = attr_value.SerializeToString() # TODO(skyewm): this creates and deletes a new TF_Status for every attr. # It might be worth creating a convenient way to re-use the same status. c_api.TF_SetAttrValueProto(op_desc, compat.as_str(name), serialized) try: c_op = c_api.TF_FinishOperation(op_desc) except errors.InvalidArgumentError as e: # Convert to ValueError for backwards compatibility. > raise ValueError(str(e)) E ValueError: Dimension 1 in both shapes must be equal, but are 6 and 3. Shapes are [4,6] and [4,3]. for 'while_2/Select_2' (op: 'Select') with input shapes: [4,3], [4,6], [4,6]. /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1867: ValueError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:170: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:177: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:182: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. 2023-07-15 05:55:50.399073: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 05:55:50.422198: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 05:55:50.422377: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55d1d266d1b0 executing computations on platform Host. Devices: 2023-07-15 05:55:50.422391: I tensorflow/compiler/xla/service/service.cc:175] StreamExecutor device (0): <undefined>, <undefined> WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:186: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:195: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. 2023-07-15 05:55:50.465857: W tensorflow/compiler/jit/mark_for_compilation_pass.cc:1412] (One-time warning): Not using XLA:CPU for cluster because envvar TF_XLA_FLAGS=--tf_xla_cpu_global_jit was not set. If you want XLA:CPU, either set that envvar, or use experimental_jit_scope to enable XLA:CPU. To confirm that XLA is active, pass --vmodule=xla_compilation_cache=1 (as a proper command-line flag, not via TF_XLA_FLAGS) or set the envvar XLA_FLAGS=--xla_hlo_profile. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2873: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation_wrapper.py:119 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:170: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:deprecation_wrapper.py:119 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:177: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:deprecation_wrapper.py:119 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:182: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:deprecation_wrapper.py:119 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:186: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:deprecation_wrapper.py:119 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:195: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:deprecation.py:323 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2873: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where =============================== warnings summary =============================== /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1286: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/util/nest.py:1287: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:601: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:635: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:645: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:61: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class ObjectIdentityDictionary(collections.MutableMapping): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/object_identity.py:112: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/training/tracking/data_structures.py:374: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable tests/keras/backend/backend_test.py:21 tests/keras/backend/backend_test.py:21 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:21: UserWarning: Could not import the CNTK backend warnings.warn('Could not import the CNTK backend') tests/keras/backend/backend_test.py:35 tests/keras/backend/backend_test.py:35 /home/user/BugsInPy/temp/projects/keras/tests/keras/backend/backend_test.py:35: UserWarning: Could not import the Theano backend warnings.warn('Could not import the Theano backend') /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:538: 24 tests with warnings /opt/conda/envs/70d512a17e79e7668f22d8292a6a3870/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py:538: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.95s call tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states ======================= 1 failed, 116 warnings in 10.88s =======================
pytest tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states
87417470c8168772559be0531e297120c569a422
tests/keras/backend/backend_test.py
keras-team__keras-10
keras-team/keras
diff --git a/keras/engine/training_utils.py b/keras/engine/training_utils.py index e8116397..d1e3f9ba 100644 --- a/keras/engine/training_utils.py +++ b/keras/engine/training_utils.py @@ -432,7 +432,8 @@ def standardize_weights(y, """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) - weight array. + weight array. If both `sample_weights` and `class_weights` are provided, + the weights are multiplied together. # Arguments y: Numpy array of model targets to be weighted. @@ -478,10 +479,6 @@ def standardize_weights(y, 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') - if sample_weight is not None and class_weight is not None: - warnings.warn('Found both `sample_weight` and `class_weight`: ' - '`class_weight` argument will be ignored.') - if sample_weight is not None: if len(sample_weight.shape) > len(y.shape): raise ValueError('Found a sample_weight with shape' + @@ -495,22 +492,24 @@ def standardize_weights(y, ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') - return sample_weight - elif isinstance(class_weight, dict): + + class_sample_weight = None + if isinstance(class_weight, dict): if len(y.shape) > 2: raise ValueError('`class_weight` not supported for ' '3+ dimensional targets.') - if y.shape[1] > 1: - y_classes = np.argmax(y, axis=1) - elif y.shape[1] == 1: - y_classes = np.reshape(y, y.shape[0]) + if len(y.shape) == 2: + if y.shape[1] > 1: + y_classes = np.argmax(y, axis=1) + elif y.shape[1] == 1: + y_classes = np.reshape(y, y.shape[0]) else: y_classes = y - weights = np.asarray([class_weight[cls] for cls in y_classes - if cls in class_weight]) + class_sample_weight = np.asarray( + [class_weight[cls] for cls in y_classes if cls in class_weight]) - if len(weights) != len(y_classes): + if len(class_sample_weight) != len(y_classes): # subtract the sets to pick all missing classes existing_classes = set(y_classes) existing_class_weight = set(class_weight.keys()) @@ -519,12 +518,19 @@ def standardize_weights(y, ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) - return weights + + if sample_weight is not None and class_sample_weight is not None: + return sample_weight * class_sample_weight + if sample_weight is not None: + return sample_weight + if class_sample_weight is not None: + return class_sample_weight + + # Everything has weight 1 by default. + if sample_weight_mode is None: + return np.ones((y.shape[0],), dtype=K.floatx()) else: - if sample_weight_mode is None: - return np.ones((y.shape[0],), dtype=K.floatx()) - else: - return np.ones((y.shape[0], y.shape[1]), dtype=K.floatx()) + return np.ones((y.shape[0], y.shape[1]), dtype=K.floatx()) def check_num_samples(ins,
diff --git a/tests/keras/engine/test_training.py b/tests/keras/engine/test_training.py index a94994139..1d7df6747 100644 --- a/tests/keras/engine/test_training.py +++ b/tests/keras/engine/test_training.py @@ -1575,5 +1575,25 @@ def test_dynamic_set_inputs(): assert preds4.shape == (1, 19) +def test_sample_weights(): + y = np.array([0, 1, 0, 0, 2]) + sample_weights = np.array([0.5, 1., 1., 0., 2.]) + class_weights = {0: 0.5, 1: 1., 2: 1.5} + + # Only `sample_weights`. + weights = training_utils.standardize_weights(y, sample_weights) + assert np.allclose(weights, sample_weights) + + # Only `class_weights`. + weights = training_utils.standardize_weights(y, class_weight=class_weights) + assert np.allclose(weights, np.array([0.5, 1., 0.5, 0.5, 1.5])) + + # Both 'sample_weights` and 'class_weights`. + weights = training_utils.standardize_weights(y, sample_weights, + class_weights) + expected = sample_weights * np.array([0.5, 1., 0.5, 0.5, 1.5]) + assert np.allclose(weights, expected) + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/engine/test_training.py::test_sample_weights [gw1] [100%] FAILED tests/keras/engine/test_training.py::test_sample_weights =================================== FAILURES =================================== _____________________________ test_sample_weights ______________________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_sample_weights(): y = np.array([0, 1, 0, 0, 2]) sample_weights = np.array([0.5, 1., 1., 0., 2.]) class_weights = {0: 0.5, 1: 1., 2: 1.5} # Only `sample_weights`. weights = training_utils.standardize_weights(y, sample_weights) assert np.allclose(weights, sample_weights) # Only `class_weights`. > weights = training_utils.standardize_weights(y, class_weight=class_weights) tests/keras/engine/test_training.py:1588: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ y = array([0, 1, 0, 0, 2]), sample_weight = None class_weight = {0: 0.5, 1: 1.0, 2: 1.5}, sample_weight_mode = None def standardize_weights(y, sample_weight=None, class_weight=None, sample_weight_mode=None): """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. # Arguments y: Numpy array of model targets to be weighted. sample_weight: User-provided `sample_weight` argument. class_weight: User-provided `class_weight` argument. sample_weight_mode: One of `None` or `"temporal"`. `"temporal"` indicated that we expect 2D weight data that will be applied to the last 2 dimensions of the targets (i.e. we are weighting timesteps, not samples). # Returns A Numpy array of target weights, one entry per sample to weight. # Raises ValueError: In case of invalid user-provided arguments. """ if sample_weight_mode is not None: if sample_weight_mode != 'temporal': raise ValueError('"sample_weight_mode ' 'should be None or "temporal". ' 'Found: ' + str(sample_weight_mode)) if len(y.shape) < 3: raise ValueError('Found a sample_weight array for ' 'an input with shape ' + str(y.shape) + '. ' 'Timestep-wise sample weighting (use of ' 'sample_weight_mode="temporal") is restricted to ' 'outputs that are at least 3D, i.e. that have ' 'a time dimension.') if sample_weight is not None and len(sample_weight.shape) != 2: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + '. ' 'In order to use timestep-wise sample weighting, ' 'you should pass a 2D sample_weight array.') else: if sample_weight is not None and len(sample_weight.shape) != 1: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + '. ' 'In order to use timestep-wise sample weights, ' 'you should specify ' 'sample_weight_mode="temporal" ' 'in compile(). If you just mean to use ' 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None and class_weight is not None: warnings.warn('Found both `sample_weight` and `class_weight`: ' '`class_weight` argument will be ignored.') if sample_weight is not None: if len(sample_weight.shape) > len(y.shape): raise ValueError('Found a sample_weight with shape' + str(sample_weight.shape) + '.' 'Expected sample_weight with rank ' 'less than or equal to ' + str(len(y.shape))) if y.shape[:sample_weight.ndim] != sample_weight.shape: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') return sample_weight elif isinstance(class_weight, dict): if len(y.shape) > 2: raise ValueError('`class_weight` not supported for ' '3+ dimensional targets.') > if y.shape[1] > 1: E IndexError: tuple index out of range keras/engine/training_utils.py:503: IndexError --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:102: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:102: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. =============================== warnings summary =============================== tests/keras/engine/test_training.py:1133 tests/keras/engine/test_training.py:1133 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:1133: DeprecationWarning: invalid escape sequence \d 'have one entry per model output. The model has \d ' tests/keras/engine/test_training.py:1138 tests/keras/engine/test_training.py:1138 /home/user/BugsInPy/temp/projects/keras/tests/keras/engine/test_training.py:1138: DeprecationWarning: invalid escape sequence \d match='The model has \d outputs, but you passed a single ' /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/engine/test_training.py::test_sample_weights - IndexError:... ======================== 1 failed, 5 warnings in 18.22s ======================== Using TensorFlow backend.
pytest tests/keras/engine/test_training.py::test_sample_weights
8f41e41eda6e8ea96403cae5798a5a89c8bb5605
tests/keras/engine/test_training.py
keras-team__keras-29
keras-team/keras
diff --git a/keras/engine/training.py b/keras/engine/training.py index 78be752b..e78477e4 100644 --- a/keras/engine/training.py +++ b/keras/engine/training.py @@ -853,6 +853,7 @@ class Model(Container): nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names) self.metrics_updates = [] self.stateful_metric_names = [] + self.stateful_metric_functions = [] with K.name_scope('metrics'): for i in range(len(self.outputs)): if i in skip_target_indices: @@ -929,6 +930,7 @@ class Model(Container): # stateful metrics (i.e. metrics layers). if isinstance(metric_fn, Layer) and metric_fn.stateful: self.stateful_metric_names.append(metric_name) + self.stateful_metric_functions.append(metric_fn) self.metrics_updates += metric_fn.updates handle_metrics(output_metrics) @@ -1174,9 +1176,8 @@ class Model(Container): for epoch in range(initial_epoch, epochs): # Reset stateful metrics - for m in self.metrics: - if isinstance(m, Layer) and m.stateful: - m.reset_states() + for m in self.stateful_metric_functions: + m.reset_states() callbacks.on_epoch_begin(epoch) epoch_logs = {} if steps_per_epoch is not None: @@ -1363,9 +1364,8 @@ class Model(Container): """ if hasattr(self, 'metrics'): - for m in self.metrics: - if isinstance(m, Layer) and m.stateful: - m.reset_states() + for m in self.stateful_metric_functions: + m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(self.metrics_names) if str(name) in self.stateful_metric_names] @@ -2185,9 +2185,8 @@ class Model(Container): # Construct epoch logs. epoch_logs = {} while epoch < epochs: - for m in self.metrics: - if isinstance(m, Layer) and m.stateful: - m.reset_states() + for m in self.stateful_metric_functions: + m.reset_states() callbacks.on_epoch_begin(epoch) steps_done = 0 batch_index = 0 @@ -2331,9 +2330,8 @@ class Model(Container): stateful_metric_indices = [] if hasattr(self, 'metrics'): - for i, m in enumerate(self.metrics): - if isinstance(m, Layer) and m.stateful: - m.reset_states() + for m in self.stateful_metric_functions: + m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(self.metrics_names) if str(name) in self.stateful_metric_names]
diff --git a/tests/keras/metrics_test.py b/tests/keras/metrics_test.py index 2e40daeda..39ad1cdbc 100644 --- a/tests/keras/metrics_test.py +++ b/tests/keras/metrics_test.py @@ -107,7 +107,8 @@ def test_sparse_top_k_categorical_accuracy(): @keras_test -def test_stateful_metrics(): [email protected]('metrics_mode', ['list', 'dict']) +def test_stateful_metrics(metrics_mode): np.random.seed(1334) class BinaryTruePositives(keras.layers.Layer): @@ -155,11 +156,17 @@ def test_stateful_metrics(): # Test on simple model inputs = keras.Input(shape=(2,)) - outputs = keras.layers.Dense(1, activation='sigmoid')(inputs) + outputs = keras.layers.Dense(1, activation='sigmoid', name='out')(inputs) model = keras.Model(inputs, outputs) - model.compile(optimizer='sgd', - loss='binary_crossentropy', - metrics=['acc', metric_fn]) + + if metrics_mode == 'list': + model.compile(optimizer='sgd', + loss='binary_crossentropy', + metrics=['acc', metric_fn]) + elif metrics_mode == 'dict': + model.compile(optimizer='sgd', + loss='binary_crossentropy', + metrics={'out': ['acc', metric_fn]}) samples = 1000 x = np.random.random((samples, 2))
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/metrics_test.py::test_stateful_metrics[dict] [gw0] [100%] FAILED tests/keras/metrics_test.py::test_stateful_metrics[dict] =================================== FAILURES =================================== _________________________ test_stateful_metrics[dict] __________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/bin/python metrics_mode = 'dict' @keras_test @pytest.mark.parametrize('metrics_mode', ['list', 'dict']) def test_stateful_metrics(metrics_mode): np.random.seed(1334) class BinaryTruePositives(keras.layers.Layer): """Stateful Metric to count the total true positives over all batches. Assumes predictions and targets of shape `(samples, 1)`. # Arguments name: String, name for the metric. """ def __init__(self, name='true_positives', **kwargs): super(BinaryTruePositives, self).__init__(name=name, **kwargs) self.stateful = True self.true_positives = K.variable(value=0, dtype='int32') def reset_states(self): K.set_value(self.true_positives, 0) def __call__(self, y_true, y_pred): """Computes the number of true positives in a batch. # Arguments y_true: Tensor, batch_wise labels y_pred: Tensor, batch_wise predictions # Returns The total number of true positives seen this epoch at the completion of the batch. """ y_true = K.cast(y_true, 'int32') y_pred = K.cast(K.round(y_pred), 'int32') correct_preds = K.cast(K.equal(y_pred, y_true), 'int32') true_pos = K.cast(K.sum(correct_preds * y_true), 'int32') current_true_pos = self.true_positives * 1 self.add_update(K.update_add(self.true_positives, true_pos), inputs=[y_true, y_pred]) return current_true_pos + true_pos metric_fn = BinaryTruePositives() config = metrics.serialize(metric_fn) metric_fn = metrics.deserialize( config, custom_objects={'BinaryTruePositives': BinaryTruePositives}) # Test on simple model inputs = keras.Input(shape=(2,)) outputs = keras.layers.Dense(1, activation='sigmoid', name='out')(inputs) model = keras.Model(inputs, outputs) if metrics_mode == 'list': model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['acc', metric_fn]) elif metrics_mode == 'dict': model.compile(optimizer='sgd', loss='binary_crossentropy', metrics={'out': ['acc', metric_fn]}) samples = 1000 x = np.random.random((samples, 2)) y = np.random.randint(2, size=(samples, 1)) val_samples = 10 val_x = np.random.random((val_samples, 2)) val_y = np.random.randint(2, size=(val_samples, 1)) # Test fit and evaluate history = model.fit(x, y, validation_data=(val_x, val_y), epochs=1, batch_size=10) outs = model.evaluate(x, y, batch_size=10) preds = model.predict(x) def ref_true_pos(y_true, y_pred): return np.sum(np.logical_and(y_pred > 0.5, y_true == 1)) # Test correctness (e.g. updates should have been run) > np.testing.assert_allclose(outs[2], ref_true_pos(y, preds), atol=1e-5) E AssertionError: E Not equal to tolerance rtol=1e-07, atol=1e-05 E E Mismatched elements: 1 / 1 (100%) E Max absolute difference: 491 E Max relative difference: 1.0293501 E x: array(968, dtype=int32) E y: array(477) tests/keras/metrics_test.py:188: AssertionError ----------------------------- Captured stdout call ----------------------------- Train on 1000 samples, validate on 10 samples Epoch 1/1 10/1000 [..............................] - ETA: 12s - loss: 1.0951 - acc: 0.3000 - true_positives: 3.0000 580/1000 [================>.............] - ETA: 0s - loss: 0.8361 - acc: 0.4707 - true_positives: 272.0000 1000/1000 [==============================] - 0s 241us/step - loss: 0.8034 - acc: 0.4900 - true_positives: 484.0000 - val_loss: 0.6407 - val_acc: 0.7000 - val_true_positives: 491.0000 10/1000 [..............................] - ETA: 0s 330/1000 [========>.....................] - ETA: 0s 830/1000 [=======================>......] - ETA: 0s 1000/1000 [==============================] - 0s 120us/step ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING:tensorflow:From /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. 2023-07-15 06:08:59.114336: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:08:59.117260: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:08:59.117400: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55d508b4ee50 executing computations on platform Host. Devices: 2023-07-15 06:08:59.117448: I tensorflow/compiler/xla/service/service.cc:158] StreamExecutor device (0): <undefined>, <undefined> ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. =============================== warnings summary =============================== /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/6653c8d2bfe512b8ea59642a1bdc72a4/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.81s call tests/keras/metrics_test.py::test_stateful_metrics[dict] (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/metrics_test.py::test_stateful_metrics[dict] - AssertionEr... ======================== 1 failed, 27 warnings in 9.01s ========================
pytest tests/keras/metrics_test.py::test_stateful_metrics[dict]
a341c014412cbfc86a9dd9816ae228e398dff3a2
tests/keras/metrics_test.py
keras-team__keras-23
keras-team/keras
diff --git a/keras/engine/sequential.py b/keras/engine/sequential.py index 37d19d0b..6def870b 100644 --- a/keras/engine/sequential.py +++ b/keras/engine/sequential.py @@ -149,8 +149,6 @@ class Sequential(Model): first_layer = layer.layers[0] while isinstance(first_layer, (Model, Sequential)): first_layer = first_layer.layers[0] - batch_shape = first_layer.batch_input_shape - dtype = first_layer.dtype if hasattr(first_layer, 'batch_input_shape'): batch_shape = first_layer.batch_input_shape
diff --git a/tests/keras/test_sequential_model.py b/tests/keras/test_sequential_model.py index c334aa3fc..a3b90b8b3 100644 --- a/tests/keras/test_sequential_model.py +++ b/tests/keras/test_sequential_model.py @@ -422,5 +422,45 @@ def test_sequential_deferred_build(): assert len(new_model.weights) == 4 +@keras_test +def test_nested_sequential_deferred_build(): + inner_model = keras.models.Sequential() + inner_model.add(keras.layers.Dense(3)) + inner_model.add(keras.layers.Dense(3)) + + model = keras.models.Sequential() + model.add(inner_model) + model.add(keras.layers.Dense(5)) + model.compile('sgd', 'mse') + + assert inner_model.built is False + assert len(inner_model.layers) == 2 + assert len(inner_model.weights) == 0 + assert model.built is False + assert len(model.layers) == 2 + assert len(model.weights) == 0 + + model.train_on_batch( + np.random.random((2, 4)), np.random.random((2, 5))) + + assert inner_model.built is True + assert len(inner_model.layers) == 2 + assert len(inner_model.weights) == 4 + assert model.built is True + assert len(model.layers) == 2 + assert len(model.weights) == 6 + + config = model.get_config() + new_model = keras.models.Sequential.from_config(config) + assert new_model.built is True + assert len(new_model.layers) == 2 + assert len(new_model.weights) == 6 + + new_inner_model = new_model.layers[0] + assert new_inner_model.built is True + assert len(new_inner_model.layers) == 2 + assert len(new_inner_model.weights) == 4 + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [0] / gw1 [0] scheduling tests via LoadScheduling ==================================== ERRORS ==================================== ____________ ERROR collecting tests/keras/test_sequential_model.py _____________ tests/keras/test_sequential_model.py:8: in <module> from keras import backend as K keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. ____________ ERROR collecting tests/keras/test_sequential_model.py _____________ tests/keras/test_sequential_model.py:8: in <module> from keras import backend as K keras/__init__.py:5: in <module> from . import applications keras/applications/__init__.py:13: in <module> keras_applications.set_keras_submodules( E AttributeError: module 'keras_applications' has no attribute 'set_keras_submodules' ------------------------------- Captured stderr -------------------------------- Using TensorFlow backend. =============================== warnings summary =============================== /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/65bf4093b0a0228acca3fe9ac48a2922/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html =========================== short test summary info ============================ ERROR tests/keras/test_sequential_model.py - AttributeError: module 'keras_ap... ERROR tests/keras/test_sequential_model.py - AttributeError: module 'keras_ap... ======================== 56 warnings, 2 errors in 9.75s ========================
pytest tests/keras/test_sequential_model.py::test_nested_sequential_deferred_build
3dcd9c767ce6875fc8b69c74971ac8a552e23131
tests/keras/test_sequential_model.py
keras-team__keras-36
keras-team/keras
diff --git a/keras/backend/tensorflow_backend.py b/keras/backend/tensorflow_backend.py index 8fdb9aa8..27f8afed 100644 --- a/keras/backend/tensorflow_backend.py +++ b/keras/backend/tensorflow_backend.py @@ -3416,10 +3416,10 @@ def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': spatial_start_dim = 1 - strides = (1, 1) + strides + (1,) + strides = (1,) + strides * 2 + (1,) else: spatial_start_dim = 2 - strides = (1, 1, 1) + strides + strides = (1, 1) + strides * 2 x = tf.expand_dims(x, spatial_start_dim) depthwise_kernel = tf.expand_dims(depthwise_kernel, 0) pointwise_kernel = tf.expand_dims(pointwise_kernel, 0)
diff --git a/tests/keras/layers/convolutional_test.py b/tests/keras/layers/convolutional_test.py index 4bb3fe584..296d9a15b 100644 --- a/tests/keras/layers/convolutional_test.py +++ b/tests/keras/layers/convolutional_test.py @@ -238,21 +238,22 @@ def test_separable_conv_1d(): num_step = 9 for padding in _convolution_paddings: - for multiplier in [1, 2]: - for dilation_rate in [1, 2]: - if padding == 'same': - continue - if dilation_rate != 1: - continue + for strides in [1, 2]: + for multiplier in [1, 2]: + for dilation_rate in [1, 2]: + if padding == 'same' and strides != 1: + continue + if dilation_rate != 1 and strides != 1: + continue - layer_test(convolutional.SeparableConv1D, - kwargs={'filters': filters, - 'kernel_size': 3, - 'padding': padding, - 'strides': 1, - 'depth_multiplier': multiplier, - 'dilation_rate': dilation_rate}, - input_shape=(num_samples, num_step, stack_size)) + layer_test(convolutional.SeparableConv1D, + kwargs={'filters': filters, + 'kernel_size': 3, + 'padding': padding, + 'strides': strides, + 'depth_multiplier': multiplier, + 'dilation_rate': dilation_rate}, + input_shape=(num_samples, num_step, stack_size)) layer_test(convolutional.SeparableConv1D, kwargs={'filters': filters,
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/convolutional_test.py::test_separable_conv_1d [gw0] [100%] FAILED tests/keras/layers/convolutional_test.py::test_separable_conv_1d =================================== FAILURES =================================== ____________________________ test_separable_conv_1d ____________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/bin/python self = <tensorflow.python.client.session.Session object at 0x7ff8b8ba9e10> fn = <function BaseSession._do_run.<locals>._run_fn at 0x7ff89c2f1bf8> args = ({<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1a62...ct of type 'TF_Output *' at 0x7ff89c1081e0> >], [<Swig Object of type 'TF_Operation *' at 0x7ff89c1a6f30>], None, None) message = 'Current implementation only supports equal length strides in the row and column dimensions.\n\t [[node separable_conv...able_conv2d/depthwise (defined at /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3432) ]]' m = <re.Match object; span=(94, 150), match='[[{{node separable_conv1d_5/separable_conv2d/dept> def _do_call(self, fn, *args): try: > return fn(*args) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1334: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ feed_dict = {<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1a62d...103971 ], [9.359914 , 4.4900694 , 4.4280233 ], [8.822814 , 8.523567 , 1.3175168 ]]], dtype=float32)} fetch_list = [<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1081e0> >] target_list = [<Swig Object of type 'TF_Operation *' at 0x7ff89c1a6f30>] options = None, run_metadata = None def _run_fn(feed_dict, fetch_list, target_list, options, run_metadata): # Ensure any changes to the graph are reflected in the runtime. self._extend_graph() return self._call_tf_sessionrun( > options, feed_dict, fetch_list, target_list, run_metadata) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1319: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <tensorflow.python.client.session.Session object at 0x7ff8b8ba9e10> options = None feed_dict = {<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1a62d...103971 ], [9.359914 , 4.4900694 , 4.4280233 ], [8.822814 , 8.523567 , 1.3175168 ]]], dtype=float32)} fetch_list = [<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1081e0> >] target_list = [<Swig Object of type 'TF_Operation *' at 0x7ff89c1a6f30>] run_metadata = None def _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata): return tf_session.TF_SessionRun_wrapper( self._session, options, feed_dict, fetch_list, target_list, > run_metadata) E tensorflow.python.framework.errors_impl.InvalidArgumentError: Current implementation only supports equal length strides in the row and column dimensions. E [[{{node separable_conv1d_5/separable_conv2d/depthwise}}]] /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1407: InvalidArgumentError During handling of the above exception, another exception occurred: @pytest.mark.skipif(K.backend() != 'tensorflow', reason='Requires TF backend') @keras_test def test_separable_conv_1d(): num_samples = 2 filters = 6 stack_size = 3 num_step = 9 for padding in _convolution_paddings: for strides in [1, 2]: for multiplier in [1, 2]: for dilation_rate in [1, 2]: if padding == 'same' and strides != 1: continue if dilation_rate != 1 and strides != 1: continue layer_test(convolutional.SeparableConv1D, kwargs={'filters': filters, 'kernel_size': 3, 'padding': padding, 'strides': strides, 'depth_multiplier': multiplier, 'dilation_rate': dilation_rate}, > input_shape=(num_samples, num_step, stack_size)) tests/keras/layers/convolutional_test.py:256: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/utils/test_utils.py:95: in layer_test actual_output = model.predict(input_data) keras/engine/training.py:1803: in predict verbose=verbose, steps=steps) keras/engine/training.py:1303: in _predict_loop batch_outs = f(ins_batch) keras/backend/tensorflow_backend.py:2475: in __call__ **self.session_kwargs) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:929: in run run_metadata_ptr) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1152: in _run feed_dict_tensor, options, run_metadata) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1328: in _do_run run_metadata) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <tensorflow.python.client.session.Session object at 0x7ff8b8ba9e10> fn = <function BaseSession._do_run.<locals>._run_fn at 0x7ff89c2f1bf8> args = ({<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x7ff89c1a62...ct of type 'TF_Output *' at 0x7ff89c1081e0> >], [<Swig Object of type 'TF_Operation *' at 0x7ff89c1a6f30>], None, None) message = 'Current implementation only supports equal length strides in the row and column dimensions.\n\t [[node separable_conv...able_conv2d/depthwise (defined at /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3432) ]]' m = <re.Match object; span=(94, 150), match='[[{{node separable_conv1d_5/separable_conv2d/dept> def _do_call(self, fn, *args): try: return fn(*args) except errors.OpError as e: message = compat.as_text(e.message) m = BaseSession._NODEDEF_NAME_RE.search(message) node_def = None op = None if m is not None: node_name = m.group(3) try: op = self._graph.get_operation_by_name(node_name) node_def = op.node_def except KeyError: pass message = error_interpolation.interpolate(message, self._graph) > raise type(e)(node_def, op, message) E tensorflow.python.framework.errors_impl.InvalidArgumentError: Current implementation only supports equal length strides in the row and column dimensions. E [[node separable_conv1d_5/separable_conv2d/depthwise (defined at /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3432) ]] E E Caused by op 'separable_conv1d_5/separable_conv2d/depthwise', defined at: E File "<string>", line 1, in <module> E File "<string>", line 8, in <module> E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 1554, in serve E SlaveGateway(io=io, id=id, _startcount=2).serve() E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 1060, in serve E self._execpool.integrate_as_primary_thread() E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 267, in integrate_as_primary_thread E self._perform_spawn(reply) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 285, in _perform_spawn E reply.run() E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 220, in run E self._result = func(*args, **kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/execnet/gateway_base.py", line 1084, in executetask E do_exec(co, loc) # noqa E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/xdist/remote.py", line 261, in <module> E config.hook.pytest_cmdline_main(config=config) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__ E return self._hookexec(self, self.get_hookimpls(), kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec E return self._inner_hookexec(hook, methods, kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda> E firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall E res = hook_impl.function(*args) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/main.py", line 240, in pytest_cmdline_main E return wrap_session(config, _main) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/main.py", line 191, in wrap_session E session.exitstatus = doit(config, session) or 0 E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/main.py", line 247, in _main E config.hook.pytest_runtestloop(session=session) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__ E return self._hookexec(self, self.get_hookimpls(), kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec E return self._inner_hookexec(hook, methods, kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda> E firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall E res = hook_impl.function(*args) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/xdist/remote.py", line 74, in pytest_runtestloop E self.run_one_test(torun) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/xdist/remote.py", line 88, in run_one_test E self.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__ E return self._hookexec(self, self.get_hookimpls(), kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec E return self._inner_hookexec(hook, methods, kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda> E firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall E res = hook_impl.function(*args) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 85, in pytest_runtest_protocol E runtestprotocol(item, nextitem=nextitem) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 100, in runtestprotocol E reports.append(call_and_report(item, "call", log)) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 186, in call_and_report E call = call_runtest_hook(item, when, **kwds) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 217, in call_runtest_hook E lambda: ihook(item=item, **kwds), when=when, reraise=reraise E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 244, in from_call E result = func() E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 217, in <lambda> E lambda: ihook(item=item, **kwds), when=when, reraise=reraise E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__ E return self._hookexec(self, self.get_hookimpls(), kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec E return self._inner_hookexec(hook, methods, kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda> E firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall E res = hook_impl.function(*args) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/runner.py", line 135, in pytest_runtest_call E item.runtest() E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/python.py", line 1477, in runtest E self.ihook.pytest_pyfunc_call(pyfuncitem=self) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__ E return self._hookexec(self, self.get_hookimpls(), kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec E return self._inner_hookexec(hook, methods, kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda> E firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall E res = hook_impl.function(*args) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/_pytest/python.py", line 182, in pytest_pyfunc_call E result = testfunction(**testargs) E File "/home/user/BugsInPy/temp/projects/keras/keras/utils/test_utils.py", line 161, in wrapper E output = func(*args, **kwargs) E File "/home/user/BugsInPy/temp/projects/keras/tests/keras/layers/convolutional_test.py", line 256, in test_separable_conv_1d E input_shape=(num_samples, num_step, stack_size)) E File "/home/user/BugsInPy/temp/projects/keras/keras/utils/test_utils.py", line 89, in layer_test E y = layer(x) E File "/home/user/BugsInPy/temp/projects/keras/keras/engine/topology.py", line 617, in __call__ E output = self.call(inputs, **kwargs) E File "/home/user/BugsInPy/temp/projects/keras/keras/layers/convolutional.py", line 1222, in call E dilation_rate=self.dilation_rate) E File "/home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py", line 3432, in separable_conv1d E data_format=tf_data_format) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/nn_impl.py", line 674, in separable_conv2d E op=op) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/nn_ops.py", line 435, in with_space_to_batch E return new_op(input, None) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/nn_ops.py", line 591, in __call__ E return self.call(inp, filter) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/nn_ops.py", line 425, in <lambda> E return lambda inp, _: op(inp, num_spatial_dims, padding) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/nn_impl.py", line 666, in op E name="depthwise") E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 2251, in depthwise_conv2d_native E dilations=dilations, name=name) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py", line 788, in _apply_op_helper E op_def=op_def) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py", line 507, in new_func E return func(*args, **kwargs) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 3300, in create_op E op_def=op_def) E File "/opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 1801, in __init__ E self._traceback = tf_stack.extract_stack() E E InvalidArgumentError (see above for traceback): Current implementation only supports equal length strides in the row and column dimensions. E [[node separable_conv1d_5/separable_conv2d/depthwise (defined at /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3432) ]] /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/client/session.py:1348: InvalidArgumentError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. 2023-07-15 06:37:07.794158: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:37:07.797357: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:37:07.797526: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55aefca57860 executing computations on platform Host. Devices: 2023-07-15 06:37:07.797539: I tensorflow/compiler/xla/service/service.cc:158] StreamExecutor device (0): <undefined>, <undefined> WARNING:tensorflow:From /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. 2023-07-15 06:37:17.983635: E tensorflow/core/common_runtime/executor.cc:624] Executor failed to create kernel. Invalid argument: Current implementation only supports equal length strides in the row and column dimensions. [[{{node separable_conv1d_5/separable_conv2d/depthwise}}]] ------------------------------ Captured log call ------------------------------- WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. =============================== warnings summary =============================== /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/91ea65510c707c6c7c6032539f2e3ff2/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 10.23s call tests/keras/layers/convolutional_test.py::test_separable_conv_1d (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/convolutional_test.py::test_separable_conv_1d - ten... ======================= 1 failed, 45 warnings in 18.34s ========================
pytest tests/keras/layers/convolutional_test.py::test_separable_conv_1d
85f011df5a5c0fcf1f01b39eca338eb6b7e58401
tests/keras/layers/convolutional_test.py
keras-team__keras-39
keras-team/keras
diff --git a/keras/utils/generic_utils.py b/keras/utils/generic_utils.py index 667e93f9..56e329e5 100644 --- a/keras/utils/generic_utils.py +++ b/keras/utils/generic_utils.py @@ -327,7 +327,7 @@ class Progbar(object): info = ' - %.0fs' % (now - self.start) if self.verbose == 1: if (not force and (now - self.last_update) < self.interval and - current < self.target): + (self.target is not None and current < self.target)): return prev_total_width = self.total_width
diff --git a/tests/keras/utils/generic_utils_test.py b/tests/keras/utils/generic_utils_test.py index 9aa2a7cb9..408b9c30e 100644 --- a/tests/keras/utils/generic_utils_test.py +++ b/tests/keras/utils/generic_utils_test.py @@ -16,8 +16,12 @@ from keras import regularizers def test_progbar(): n = 2 input_arr = np.random.random((n, n, n)) + bar = Progbar(n) + for i, arr in enumerate(input_arr): + bar.update(i, list(arr)) + bar = Progbar(None) for i, arr in enumerate(input_arr): bar.update(i, list(arr))
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/utils/generic_utils_test.py::test_progbar [gw1] [100%] FAILED tests/keras/utils/generic_utils_test.py::test_progbar =================================== FAILURES =================================== _________________________________ test_progbar _________________________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python @keras_test def test_progbar(): n = 2 input_arr = np.random.random((n, n, n)) bar = Progbar(n) for i, arr in enumerate(input_arr): bar.update(i, list(arr)) bar = Progbar(None) for i, arr in enumerate(input_arr): > bar.update(i, list(arr)) tests/keras/utils/generic_utils_test.py:26: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <keras.utils.generic_utils.Progbar object at 0x7f7d265110f0>, current = 1 values = [array([0.80476831, 0.2067068 ]), array([0.60822768, 0.53821 ])] force = False def update(self, current, values=None, force=False): """Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. force: Whether to force visual progress update. """ values = values or [] for k, v in values: if k not in self.sum_values: self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far] self.unique_values.append(k) else: self.sum_values[k][0] += v * (current - self.seen_so_far) self.sum_values[k][1] += (current - self.seen_so_far) self.seen_so_far = current now = time.time() info = ' - %.0fs' % (now - self.start) if self.verbose == 1: if (not force and (now - self.last_update) < self.interval and > current < self.target): E TypeError: '<' not supported between instances of 'int' and 'NoneType' keras/utils/generic_utils.py:330: TypeError ----------------------------- Captured stdout call ----------------------------- 0/2 [..............................] - ETA: 0s - 0.8063144332973256: 0.0000e+00 - 0.5342672310891231: 0.0000e+00 0/Unknown - 0s 0us/step - 0.8063144332973256: 0.0000e+00 - 0.5342672310891231: 0.0000e+00 =============================== warnings summary =============================== /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/utils/generic_utils_test.py::test_progbar - TypeError: '<'... ======================== 1 failed, 55 warnings in 5.22s ========================
pytest tests/keras/utils/generic_utils_test.py::test_progbar
3a431ea52d090fb3ef8a1e0e5d7f796d9a42e097
tests/keras/utils/generic_utils_test.py
keras-team__keras-35
keras-team/keras
diff --git a/keras/preprocessing/image.py b/keras/preprocessing/image.py index 97d97792..838d7bc3 100644 --- a/keras/preprocessing/image.py +++ b/keras/preprocessing/image.py @@ -580,8 +580,6 @@ class ImageDataGenerator(object): # Returns The inputs, normalized. """ - if self.preprocessing_function: - x = self.preprocessing_function(x) if self.rescale: x *= self.rescale if self.samplewise_center: @@ -951,6 +949,8 @@ class NumpyArrayIterator(Iterator): dtype=K.floatx()) for i, j in enumerate(index_array): x = self.x[j] + if self.image_data_generator.preprocessing_function: + x = self.image_data_generator.preprocessing_function(x) x = self.image_data_generator.random_transform(x.astype(K.floatx())) x = self.image_data_generator.standardize(x) batch_x[i] = x @@ -1227,8 +1227,21 @@ class DirectoryIterator(Iterator): fname = self.filenames[j] img = load_img(os.path.join(self.directory, fname), grayscale=grayscale, - target_size=self.target_size, + target_size=None, interpolation=self.interpolation) + if self.image_data_generator.preprocessing_function: + img = self.image_data_generator.preprocessing_function(img) + if self.target_size is not None: + width_height_tuple = (self.target_size[1], self.target_size[0]) + if img.size != width_height_tuple: + if self.interpolation not in _PIL_INTERPOLATION_METHODS: + raise ValueError( + 'Invalid interpolation method {} specified. Supported ' + 'methods are {}'.format( + self.interpolation, + ", ".join(_PIL_INTERPOLATION_METHODS.keys()))) + resample = _PIL_INTERPOLATION_METHODS[self.interpolation] + img = img.resize(width_height_tuple, resample) x = img_to_array(img, data_format=self.data_format) x = self.image_data_generator.random_transform(x) x = self.image_data_generator.standardize(x)
diff --git a/tests/keras/preprocessing/image_test.py b/tests/keras/preprocessing/image_test.py index 0c81cb582..bdc06ae1d 100644 --- a/tests/keras/preprocessing/image_test.py +++ b/tests/keras/preprocessing/image_test.py @@ -235,6 +235,29 @@ class TestImage(object): with pytest.raises(ValueError): x1, y1 = dir_seq[9] + # Test Preprocessing before resize + def preprocess_test(img): + return img.resize((1, 1)) + + generator = image.ImageDataGenerator(preprocessing_function=preprocess_test) + dir_seq = generator.flow_from_directory(str(tmpdir), + target_size=(26, 26), + color_mode='rgb', + batch_size=1, + class_mode='categorical') + + gen_x1, gen_y1 = dir_seq[1] + + test_x1 = image.load_img(os.path.join(dir_seq.directory, dir_seq.filenames[1]), + grayscale=False) + test_x1 = preprocess_test(test_x1) + test_x1 = test_x1.resize((26, 26)) + test_x1 = image.img_to_array(test_x1) + test_x1 = dir_seq.image_data_generator.random_transform(test_x1) + test_x1 = dir_seq.image_data_generator.standardize(test_x1) + + assert gen_x1.shape[1:] == test_x1.shape + def test_directory_iterator_class_mode_input(self, tmpdir): tmpdir.join('class-1').mkdir()
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator [gw0] [100%] FAILED tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator =================================== FAILURES =================================== ______________________ TestImage.test_directory_iterator _______________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/bin/python self = <image_test.TestImage object at 0x7fb9dbb68518> tmpdir = local('/tmp/pytest-of-root/pytest-80/popen-gw0/test_directory_iterator0') def test_directory_iterator(self, tmpdir): num_classes = 2 # create folders and subfolders paths = [] for cl in range(num_classes): class_directory = 'class-{}'.format(cl) classpaths = [ class_directory, os.path.join(class_directory, 'subfolder-1'), os.path.join(class_directory, 'subfolder-2'), os.path.join(class_directory, 'subfolder-1', 'sub-subfolder') ] for path in classpaths: tmpdir.join(path).mkdir() paths.append(classpaths) # save the images in the paths count = 0 filenames = [] for test_images in self.all_test_images: for im in test_images: # rotate image class im_class = count % num_classes # rotate subfolders classpaths = paths[im_class] filename = os.path.join(classpaths[count % len(classpaths)], 'image-{}.jpg'.format(count)) filenames.append(filename) im.save(str(tmpdir / filename)) count += 1 # create iterator generator = image.ImageDataGenerator() dir_iterator = generator.flow_from_directory(str(tmpdir)) # check number of classes and images assert len(dir_iterator.class_indices) == num_classes assert len(dir_iterator.classes) == count assert set(dir_iterator.filenames) == set(filenames) # Test invalid use cases with pytest.raises(ValueError): generator.flow_from_directory(str(tmpdir), color_mode='cmyk') with pytest.raises(ValueError): generator.flow_from_directory(str(tmpdir), class_mode='output') # Test usage as Sequence generator = image.ImageDataGenerator() dir_seq = generator.flow_from_directory(str(tmpdir), target_size=(26, 26), color_mode='rgb', batch_size=3, class_mode='categorical') assert len(dir_seq) == count // 3 + 1 x1, y1 = dir_seq[1] assert x1.shape == (3, 26, 26, 3) assert y1.shape == (3, num_classes) x1, y1 = dir_seq[5] with pytest.raises(ValueError): x1, y1 = dir_seq[9] # Test Preprocessing before resize def preprocess_test(img): return img.resize((1, 1)) generator = image.ImageDataGenerator(preprocessing_function=preprocess_test) dir_seq = generator.flow_from_directory(str(tmpdir), target_size=(26, 26), color_mode='rgb', batch_size=1, class_mode='categorical') > gen_x1, gen_y1 = dir_seq[1] tests/keras/preprocessing/image_test.py:249: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/preprocessing/image.py:827: in __getitem__ return self._get_batches_of_transformed_samples(index_array) keras/preprocessing/image.py:1234: in _get_batches_of_transformed_samples x = self.image_data_generator.standardize(x) keras/preprocessing/image.py:584: in standardize x = self.preprocessing_function(x) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ img = array([[[ 45., 53., 29.], [131., 143., 119.], [131., 143., 119.], ..., [ 43., 42., ...29.], ..., [118., 105., 122.], [118., 105., 122.], [101., 75., 102.]]], dtype=float32) def preprocess_test(img): > return img.resize((1, 1)) E ValueError: cannot resize an array that references or is referenced E by another array in this way. E Use the np.resize function or refcheck=False tests/keras/preprocessing/image_test.py:240: ValueError ----------------------------- Captured stdout call ----------------------------- Found 16 images belonging to 2 classes. Found 16 images belonging to 2 classes. Found 16 images belonging to 2 classes. =============================== warnings summary =============================== /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:823: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Mapping", _collections.Mapping) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/util/nest.py:824: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working _pywrap_tensorflow.RegisterType("Sequence", _collections.Sequence) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:312: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ListWrapper(List, collections.MutableSequence, /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/data_structures.py:546: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _DictWrapper(Mapping, collections.MutableMapping): /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/checkpointable/util.py:448: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working class _ObjectIdentitySet(collections.MutableSet): /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/tensorflow/python/training/adam.py:95: DeprecationWarning: invalid escape sequence \_ """ /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/30e8368b55e669bfee75fe8c0764efb3/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.50s call tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator 0.01s teardown tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator 0.01s setup tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator =========================== short test summary info ============================ FAILED tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator ======================= 1 failed, 45 warnings in 12.28s ========================
pytest tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator
06eaeebecfb73c23bfd531013ca172ee3bf5069c
tests/keras/preprocessing/image_test.py
keras-team__keras-8
keras-team/keras
diff --git a/keras/engine/network.py b/keras/engine/network.py index 7d36df7a..e5daf0bb 100644 --- a/keras/engine/network.py +++ b/keras/engine/network.py @@ -958,12 +958,28 @@ class Network(Layer): unprocessed_nodes = {} def add_unprocessed_node(layer, node_data): + """Add node to layer list + + Args: + layer: layer object + node_data: Node data specifying layer call + """ if layer not in unprocessed_nodes: unprocessed_nodes[layer] = [node_data] else: unprocessed_nodes[layer].append(node_data) def process_node(layer, node_data): + """Reconstruct node by linking to inbound layers + + Args: + layer: Layer to process + node_data: List of layer configs + + Raises: + ValueError: For incorrect layer config + LookupError: If layer required is not found + """ input_tensors = [] for input_data in node_data: inbound_layer_name = input_data[0] @@ -976,12 +992,14 @@ class Network(Layer): else: raise ValueError('Improperly formatted model config.') inbound_layer = created_layers[inbound_layer_name] + # Raise an error if the corresponding layer node + # has not yet been created if len(inbound_layer._inbound_nodes) <= inbound_node_index: - add_unprocessed_node(layer, node_data) - return + raise LookupError inbound_node = inbound_layer._inbound_nodes[inbound_node_index] input_tensors.append( inbound_node.output_tensors[inbound_tensor_index]) + # Call layer on its inputs, thus creating the node # and building the layer if needed. if input_tensors: @@ -1017,6 +1035,7 @@ class Network(Layer): # First, we create all layers and enqueue nodes to be processed for layer_data in config['layers']: process_layer(layer_data) + # Then we process nodes in order of layer depth. # Nodes that cannot yet be processed (if the inbound node # does not yet exist) are re-enqueued, and the process @@ -1024,10 +1043,33 @@ class Network(Layer): while unprocessed_nodes: for layer_data in config['layers']: layer = created_layers[layer_data['name']] + + # Process all nodes in layer, if not yet processed if layer in unprocessed_nodes: - for node_data in unprocessed_nodes.pop(layer): - process_node(layer, node_data) + node_data_list = unprocessed_nodes[layer] + + # Process nodes in order + node_index = 0 + while node_index < len(node_data_list): + node_data = node_data_list[node_index] + try: + process_node(layer, node_data) + + # If the node does not have all inbound layers + # available, stop processing and continue later + except LookupError: + break + + node_index += 1 + + # If not all nodes processed then store unprocessed nodes + if node_index < len(node_data_list): + unprocessed_nodes[layer] = node_data_list[node_index:] + # If all nodes processed remove the layer + else: + del unprocessed_nodes[layer] + # Create lits of input and output tensors and return new class name = config.get('name') input_tensors = [] output_tensors = []
diff --git a/tests/keras/engine/test_topology.py b/tests/keras/engine/test_topology.py index 9f5c2eebf..9813adbce 100644 --- a/tests/keras/engine/test_topology.py +++ b/tests/keras/engine/test_topology.py @@ -760,6 +760,43 @@ def test_layer_sharing_at_heterogeneous_depth_with_concat(): np.testing.assert_allclose(output_val, output_val_2, atol=1e-6) +def test_layer_sharing_at_heterogeneous_depth_order(): + # This tests for the bug in this issue + # https://github.com/keras-team/keras/issues/11159 + # It occurs with layer sharing at heterogeneous depth when + # the layers need to be applied in an order that differs from + # the order that occurs in the config. + + input_shape = (1, 12) + input_layer = Input(shape=input_shape) + + A = Dense(12, name='layer_a') + r1 = layers.Reshape((12,))(input_layer) + Aout1 = A(r1) + + r2 = layers.Reshape((12,))(A(input_layer)) + Aout2 = A(r2) + + # Note: if the order of the layers in the concat is + # changed to ([Aout1, Aout2]) the bug doesn't trigger + c1 = layers.concatenate([Aout2, Aout1]) + output = Dense(2, name='layer_b')(c1) + + M = Model(inputs=input_layer, outputs=output) + + x_val = np.random.random((10,) + input_shape) + output_val = M.predict(x_val) + + config = M.get_config() + weights = M.get_weights() + + M2 = Model.from_config(config) + M2.set_weights(weights) + + output_val_2 = M2.predict(x_val) + np.testing.assert_allclose(output_val, output_val_2, atol=1e-6) + + def test_multi_output_mask(): """Fixes #7589""" class TestMultiOutputLayer(Layer):
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order [gw0] [100%] FAILED tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order =================================== FAILURES =================================== _______________ test_layer_sharing_at_heterogeneous_depth_order ________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_layer_sharing_at_heterogeneous_depth_order(): # This tests for the bug in this issue # https://github.com/keras-team/keras/issues/11159 # It occurs with layer sharing at heterogeneous depth when # the layers need to be applied in an order that differs from # the order that occurs in the config. input_shape = (1, 12) input_layer = Input(shape=input_shape) A = Dense(12, name='layer_a') r1 = layers.Reshape((12,))(input_layer) Aout1 = A(r1) r2 = layers.Reshape((12,))(A(input_layer)) Aout2 = A(r2) # Note: if the order of the layers in the concat is # changed to ([Aout1, Aout2]) the bug doesn't trigger c1 = layers.concatenate([Aout2, Aout1]) output = Dense(2, name='layer_b')(c1) M = Model(inputs=input_layer, outputs=output) x_val = np.random.random((10,) + input_shape) output_val = M.predict(x_val) config = M.get_config() weights = M.get_weights() > M2 = Model.from_config(config) tests/keras/engine/test_topology.py:793: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/engine/network.py:1029: in from_config process_node(layer, node_data) keras/engine/network.py:988: in process_node layer(unpack_singleton(input_tensors), **kwargs) keras/engine/base_layer.py:431: in __call__ self.build(unpack_singleton(input_shapes)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <keras.layers.merge.Concatenate object at 0x7ff8986db8d0> input_shape = [(None, 12), (None, 1, 12)] def build(self, input_shape): # Used purely for shape validation. if not isinstance(input_shape, list) or len(input_shape) < 2: raise ValueError('A `Concatenate` layer should be called ' 'on a list of at least 2 inputs') if all([shape is None for shape in input_shape]): return reduced_inputs_shapes = [list(shape) for shape in input_shape] shape_set = set() for i in range(len(reduced_inputs_shapes)): del reduced_inputs_shapes[i][self.axis] shape_set.add(tuple(reduced_inputs_shapes[i])) if len(shape_set) > 1: raise ValueError('A `Concatenate` layer requires ' 'inputs with matching shapes ' 'except for the concat axis. ' > 'Got inputs shapes: %s' % (input_shape)) E ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 12), (None, 1, 12)] keras/layers/merge.py:362: ValueError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4377: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:524: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4377: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: 13 tests with warnings /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.57s call tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order ======================= 1 failed, 14 warnings in 16.40s ======================== Using TensorFlow backend.
pytest tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order
87540a2a2f42e00c4a2ca7ca35d19f96e62e6cb0
tests/keras/engine/test_topology.py
keras-team__keras-17
keras-team/keras
diff --git a/keras/metrics.py b/keras/metrics.py index 3d5df23b..7c89702e 100644 --- a/keras/metrics.py +++ b/keras/metrics.py @@ -34,7 +34,8 @@ def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): - return K.cast(K.equal(K.max(y_true, axis=-1), + # flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,) + return K.cast(K.equal(K.flatten(y_true), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx())
diff --git a/tests/keras/metrics_test.py b/tests/keras/metrics_test.py index 07ac08460..f4ab14a62 100644 --- a/tests/keras/metrics_test.py +++ b/tests/keras/metrics_test.py @@ -47,6 +47,18 @@ def test_sparse_metrics(): assert K.eval(metric(y_a, y_b)).shape == (6,) +@keras_test +def test_sparse_categorical_accuracy_correctness(): + y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx()) + y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx()) + # use one_hot embedding to convert sparse labels to equivalent dense labels + y_a_dense_labels = K.cast(K.one_hot(K.cast(y_a, dtype='int32'), num_classes=7), + dtype=K.floatx()) + sparse_categorical_acc = metrics.sparse_categorical_accuracy(y_a, y_b) + categorical_acc = metrics.categorical_accuracy(y_a_dense_labels, y_b) + assert np.allclose(K.eval(sparse_categorical_acc), K.eval(categorical_acc)) + + def test_serialize(): '''This is a mock 'round trip' of serialize and deserialize. '''
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: xdist-1.32.0, forked-1.1.3, flaky-3.6.1 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness [gw1] [100%] FAILED tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness =================================== FAILURES =================================== _________________ test_sparse_categorical_accuracy_correctness _________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python @keras_test def test_sparse_categorical_accuracy_correctness(): y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx()) y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx()) # use one_hot embedding to convert sparse labels to equivalent dense labels y_a_dense_labels = K.cast(K.one_hot(K.cast(y_a, dtype='int32'), num_classes=7), dtype=K.floatx()) sparse_categorical_acc = metrics.sparse_categorical_accuracy(y_a, y_b) categorical_acc = metrics.categorical_accuracy(y_a_dense_labels, y_b) > assert np.allclose(K.eval(sparse_categorical_acc), K.eval(categorical_acc)) E AssertionError: assert False E + where False = <function allclose at 0x7fa58c1069d8>(array([0., 0., 0., 0., 0., 0.], dtype=float32), array([0., 0., 0., 0., 1., 0.], dtype=float32)) E + where <function allclose at 0x7fa58c1069d8> = np.allclose E + and array([0., 0., 0., 0., 0., 0.], dtype=float32) = <function eval at 0x7fa52409ab70>(<tf.Tensor 'Cast_2:0' shape=(6,) dtype=float32>) E + where <function eval at 0x7fa52409ab70> = K.eval E + and array([0., 0., 0., 0., 1., 0.], dtype=float32) = <function eval at 0x7fa52409ab70>(<tf.Tensor 'Cast_3:0' shape=(6,) dtype=float32>) E + where <function eval at 0x7fa52409ab70> = K.eval tests/keras/metrics_test.py:59: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:186: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. 2023-07-15 05:50:34.022960: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: FMA 2023-07-15 05:50:34.053679: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2593905000 Hz 2023-07-15 05:50:34.057779: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55b4d01e6a20 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 05:50:34.057826: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 05:50:34.059406: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 05:50:34.059431: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 05:50:34.059452: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (f9db9463f2fb): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:186: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. =============================== warnings summary =============================== /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.18s call tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness ======================== 1 failed, 57 warnings in 8.95s ========================
pytest tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness
c913b6da92f6ab9a3f4c897caa4085e782a14680
tests/keras/metrics_test.py
keras-team__keras-38
keras-team/keras
diff --git a/keras/layers/recurrent.py b/keras/layers/recurrent.py index 59046d78..89983d8e 100644 --- a/keras/layers/recurrent.py +++ b/keras/layers/recurrent.py @@ -106,7 +106,7 @@ class StackedRNNCells(Layer): output_dim = cell.state_size[0] else: output_dim = cell.state_size - input_shape = (input_shape[0], input_shape[1], output_dim) + input_shape = (input_shape[0], output_dim) self.built = True def get_config(self):
diff --git a/tests/keras/layers/recurrent_test.py b/tests/keras/layers/recurrent_test.py index 820935b7c..4fd407ff9 100644 --- a/tests/keras/layers/recurrent_test.py +++ b/tests/keras/layers/recurrent_test.py @@ -517,6 +517,9 @@ def test_minimal_rnn_cell_layer(): super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): + # no time axis in the input shape passed to RNN cells + assert len(input_shape) == 2 + self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel')
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: httpbin-1.0.0, forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer [gw0] [100%] FAILED tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer =================================== FAILURES =================================== _________________________ test_minimal_rnn_cell_layer __________________________ [gw0] linux -- Python 3.7.3 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/bin/python @keras_test def test_minimal_rnn_cell_layer(): class MinimalRNNCell(keras.layers.Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): # no time axis in the input shape passed to RNN cells assert len(input_shape) == 2 self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = keras.backend.dot(inputs, self.kernel) output = h + keras.backend.dot(prev_output, self.recurrent_kernel) return output, [output] def get_config(self): config = {'units': self.units} base_config = super(MinimalRNNCell, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = keras.Input((None, 5)) cell = MinimalRNNCell(32) layer = recurrent.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) y_np = model.predict(x_np) weights = model.get_weights() config = layer.get_config() with keras.utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}): layer = recurrent.RNN.from_config(config) y = layer(x) model = keras.models.Model(x, y) model.set_weights(weights) y_np_2 = model.predict(x_np) assert_allclose(y_np, y_np_2, atol=1e-4) # Test stacking. cells = [MinimalRNNCell(8), MinimalRNNCell(12), MinimalRNNCell(32)] layer = recurrent.RNN(cells) > y = layer(x) tests/keras/layers/recurrent_test.py:570: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/layers/recurrent.py:488: in __call__ return super(RNN, self).__call__(inputs, **kwargs) keras/engine/topology.py:590: in __call__ self.build(input_shapes[0]) keras/layers/recurrent.py:450: in build self.cell.build(step_input_shape) keras/layers/recurrent.py:104: in build cell.build(input_shape) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <recurrent_test.test_minimal_rnn_cell_layer.<locals>.MinimalRNNCell object at 0x7fe10404ff28> input_shape = (None, 5, 8) def build(self, input_shape): # no time axis in the input shape passed to RNN cells > assert len(input_shape) == 2 E assert 3 == 2 E +3 E -2 tests/keras/layers/recurrent_test.py:521: AssertionError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:504: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3828: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:744: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:960: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2496: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:166: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:171: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. 2023-07-15 06:45:03.924535: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2023-07-15 06:45:03.931391: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3600000000 Hz 2023-07-15 06:45:03.931579: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x558c9c5c9d80 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2023-07-15 06:45:03.931592: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2023-07-15 06:45:03.932756: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2023-07-15 06:45:03.932772: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: UNKNOWN ERROR (303) 2023-07-15 06:45:03.932788: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (8cd2fa7be075): /proc/driver/nvidia/version does not exist WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:180: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:189: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:196: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:504: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3828: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:744: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:960: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2496: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:166: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:171: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:180: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:189: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:196: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead. =============================== warnings summary =============================== /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: 15 tests with warnings /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/66f557d45597d0371c1c7f7e137dee51/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 10 test durations =========================== 0.56s call tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer - as... ======================= 1 failed, 71 warnings in 10.63s ========================
pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer
53ec990d54130dd0a457dd235c93d39de32d571d
tests/keras/layers/recurrent_test.py
keras-team__keras-15
keras-team/keras
diff --git a/keras/callbacks.py b/keras/callbacks.py index ad3522d6..8c6f70c6 100644 --- a/keras/callbacks.py +++ b/keras/callbacks.py @@ -12,6 +12,8 @@ import numpy as np import time import json import warnings +import io +import sys from collections import deque from collections import OrderedDict @@ -1122,7 +1124,12 @@ class CSVLogger(Callback): self.writer = None self.keys = None self.append_header = True - self.file_flags = 'b' if six.PY2 and os.name == 'nt' else '' + if six.PY2: + self.file_flags = 'b' + self._open_args = {} + else: + self.file_flags = '' + self._open_args = {'newline': '\n'} super(CSVLogger, self).__init__() def on_train_begin(self, logs=None): @@ -1130,9 +1137,12 @@ class CSVLogger(Callback): if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) - self.csv_file = open(self.filename, 'a' + self.file_flags) + mode = 'a' else: - self.csv_file = open(self.filename, 'w' + self.file_flags) + mode = 'w' + self.csv_file = io.open(self.filename, + mode + self.file_flags, + **self._open_args) def on_epoch_end(self, epoch, logs=None): logs = logs or {} @@ -1156,9 +1166,12 @@ class CSVLogger(Callback): if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep - + fieldnames = ['epoch'] + self.keys + if six.PY2: + fieldnames = [unicode(x) for x in fieldnames] self.writer = csv.DictWriter(self.csv_file, - fieldnames=['epoch'] + self.keys, dialect=CustomDialect) + fieldnames=fieldnames, + dialect=CustomDialect) if self.append_header: self.writer.writeheader()
diff --git a/tests/keras/test_callbacks.py b/tests/keras/test_callbacks.py index 6e9c781fe..e83eb8b51 100644 --- a/tests/keras/test_callbacks.py +++ b/tests/keras/test_callbacks.py @@ -556,11 +556,15 @@ def test_CSVLogger(tmpdir): # case 3, reuse of CSVLogger object model.fit(X_train, y_train, batch_size=batch_size, - validation_data=(X_test, y_test), callbacks=cbks, epochs=1) + validation_data=(X_test, y_test), callbacks=cbks, epochs=2) import re with open(filepath) as csvfile: - output = " ".join(csvfile.readlines()) + list_lines = csvfile.readlines() + for line in list_lines: + assert line.count(sep) == 4 + assert len(list_lines) == 5 + output = " ".join(list_lines) assert len(re.findall('epoch', output)) == 1 os.remove(filepath)
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/keras/test_callbacks.py::test_CSVLogger [gw0] [100%] PASSED tests/keras/test_callbacks.py::test_CSVLogger =============================== warnings summary =============================== /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/h5py/__init__.py:46: DeprecationWarning: `np.typeDict` is a deprecated alias for `np.sctypeDict`. from ._conv import register_converters as _register_converters /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/pywrap_tensorflow_internal.py:15: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:597: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:605: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:639: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/dtypes.py:649: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:106: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:108: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:10: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _nlv = LooseVersion(_np_version) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:11: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p14 = _nlv < LooseVersion("1.14") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:12: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p15 = _nlv < LooseVersion("1.15") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:13: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p16 = _nlv < LooseVersion("1.16") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:14: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p17 = _nlv < LooseVersion("1.17") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/__init__.py:15: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. _np_version_under1p18 = _nlv < LooseVersion("1.18") /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. other = LooseVersion(other) /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/compat/numpy/function.py:114: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(_np_version) >= LooseVersion("1.17.0"): /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/pandas/_testing.py:24: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations import pandas._libs.testing as _testing /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:568: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.object, string), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:569: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations (np.bool, bool), /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:593: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:597: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:614: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_STRING_REF: np.object, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:619: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations types_pb2.DT_BOOL_REF: np.bool, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:100: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.object: SlowAppendObjectArrayToTensorProto, /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorboard/util/tensor_util.py:101: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.bool: SlowAppendBoolArrayToTensorProto, keras/callbacks.py:18 keras/callbacks.py:18 /home/user/BugsInPy/temp/projects/keras/keras/callbacks.py:18: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/a0a5407915338c9fac99516b5bd41c30/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.58s call tests/keras/test_callbacks.py::test_CSVLogger (0.00 durations hidden. Use -vv to show these durations.) ======================== 1 passed, 59 warnings in 2.36s ========================
pytest tests/keras/test_callbacks.py::test_CSVLogger
5b6243485acc20cc36f2db4f258512c332d691ec
tests/keras/test_callbacks.py
keras-team__keras-11
keras-team/keras
diff --git a/keras/engine/training_generator.py b/keras/engine/training_generator.py index 55e817a1..f74eddf8 100644 --- a/keras/engine/training_generator.py +++ b/keras/engine/training_generator.py @@ -7,6 +7,7 @@ from __future__ import print_function import warnings import numpy as np +from .training_utils import is_sequence from .training_utils import iter_sequence_infinite from .. import backend as K from ..utils.data_utils import Sequence @@ -40,15 +41,15 @@ def fit_generator(model, if do_validation: model._make_test_function() - is_sequence = isinstance(generator, Sequence) - if not is_sequence and use_multiprocessing and workers > 1: + use_sequence_api = is_sequence(generator) + if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps_per_epoch is None: - if is_sequence: + if use_sequence_api: steps_per_epoch = len(generator) else: raise ValueError('`steps_per_epoch=None` is only valid for a' @@ -59,10 +60,11 @@ def fit_generator(model, # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks + val_use_sequence_api = is_sequence(validation_data) val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or - isinstance(validation_data, Sequence)) - if (val_gen and not isinstance(validation_data, Sequence) and + val_use_sequence_api) + if (val_gen and not val_use_sequence_api and not validation_steps): raise ValueError('`validation_steps=None` is only valid for a' ' generator based on the `keras.utils.Sequence`' @@ -108,7 +110,7 @@ def fit_generator(model, if val_gen and workers > 0: # Create an Enqueuer that can be reused val_data = validation_data - if isinstance(val_data, Sequence): + if is_sequence(val_data): val_enqueuer = OrderedEnqueuer( val_data, use_multiprocessing=use_multiprocessing) @@ -122,7 +124,7 @@ def fit_generator(model, val_enqueuer_gen = val_enqueuer.get() elif val_gen: val_data = validation_data - if isinstance(val_data, Sequence): + if is_sequence(val_data): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation_steps or len(val_data) else: @@ -149,7 +151,7 @@ def fit_generator(model, cbk.validation_data = val_data if workers > 0: - if is_sequence: + if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing, @@ -161,7 +163,7 @@ def fit_generator(model, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - if is_sequence: + if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_generator = generator @@ -284,15 +286,15 @@ def evaluate_generator(model, generator, steps_done = 0 outs_per_batch = [] batch_sizes = [] - is_sequence = isinstance(generator, Sequence) - if not is_sequence and use_multiprocessing and workers > 1: + use_sequence_api = is_sequence(generator) + if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: - if is_sequence: + if use_sequence_api: steps = len(generator) else: raise ValueError('`steps=None` is only valid for a generator' @@ -303,7 +305,7 @@ def evaluate_generator(model, generator, try: if workers > 0: - if is_sequence: + if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing) @@ -314,7 +316,7 @@ def evaluate_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - if is_sequence: + if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_generator = generator @@ -387,15 +389,15 @@ def predict_generator(model, generator, steps_done = 0 all_outs = [] - is_sequence = isinstance(generator, Sequence) - if not is_sequence and use_multiprocessing and workers > 1: + use_sequence_api = is_sequence(generator) + if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: - if is_sequence: + if use_sequence_api: steps = len(generator) else: raise ValueError('`steps=None` is only valid for a generator' @@ -406,7 +408,7 @@ def predict_generator(model, generator, try: if workers > 0: - if is_sequence: + if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing) @@ -417,7 +419,7 @@ def predict_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: - if is_sequence: + if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_generator = generator diff --git a/keras/engine/training_utils.py b/keras/engine/training_utils.py index ea22fc5a..26674ba4 100644 --- a/keras/engine/training_utils.py +++ b/keras/engine/training_utils.py @@ -10,6 +10,7 @@ import warnings from .. import backend as K from .. import losses +from ..utils import Sequence from ..utils.generic_utils import to_list @@ -589,3 +590,17 @@ def iter_sequence_infinite(seq): while True: for item in seq: yield item + + +def is_sequence(seq): + """Determine if an object follows the Sequence API. + + # Arguments + seq: a possible Sequence object + + # Returns + boolean, whether the object follows the Sequence API. + """ + # TODO Dref360: Decide which pattern to follow. First needs a new TF Version. + return (getattr(seq, 'use_sequence_api', False) + or set(dir(Sequence())).issubset(set(dir(seq) + ['use_sequence_api']))) diff --git a/keras/utils/data_utils.py b/keras/utils/data_utils.py index 51088192..492aa513 100644 --- a/keras/utils/data_utils.py +++ b/keras/utils/data_utils.py @@ -341,6 +341,8 @@ class Sequence(object): ``` """ + use_sequence_api = True + @abstractmethod def __getitem__(self, index): """Gets batch at position `index`. diff --git a/tests/keras/utils/data_utils_test.py b/tests/keras/utils/data_utils_test.py index a825c53f..8e367ff4 100644 --- a/tests/keras/utils/data_utils_test.py +++ b/tests/keras/utils/data_utils_test.py @@ -22,7 +22,7 @@ from keras.utils.data_utils import validate_file from keras import backend as K pytestmark = pytest.mark.skipif( - K.backend() == 'tensorflow', + K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, reason='Temporarily disabled until the use_multiprocessing problem is solved') if sys.version_info < (3,): diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index f22cc40e..e8269d46 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -9,7 +9,7 @@ from keras.utils import Sequence from keras import backend as K pytestmark = pytest.mark.skipif( - K.backend() == 'tensorflow', + K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, reason='Temporarily disabled until the use_multiprocessing problem is solved') STEPS_PER_EPOCH = 100
diff --git a/tests/integration_tests/test_image_data_tasks.py b/tests/integration_tests/test_image_data_tasks.py index 4ba81028c..f0294d6c8 100644 --- a/tests/integration_tests/test_image_data_tasks.py +++ b/tests/integration_tests/test_image_data_tasks.py @@ -2,6 +2,7 @@ from __future__ import print_function import numpy as np import pytest +from keras.preprocessing.image import ImageDataGenerator from keras.utils.test_utils import get_test_data from keras.models import Sequential from keras import layers @@ -41,5 +42,39 @@ def test_image_classification(): model = Sequential.from_config(config) +def test_image_data_generator_training(): + np.random.seed(1337) + img_gen = ImageDataGenerator(rescale=1.) # Dummy ImageDataGenerator + input_shape = (16, 16, 3) + (x_train, y_train), (x_test, y_test) = get_test_data(num_train=500, + num_test=200, + input_shape=input_shape, + classification=True, + num_classes=4) + y_train = to_categorical(y_train) + y_test = to_categorical(y_test) + + model = Sequential([ + layers.Conv2D(filters=8, kernel_size=3, + activation='relu', + input_shape=input_shape), + layers.MaxPooling2D(pool_size=2), + layers.Conv2D(filters=4, kernel_size=(3, 3), + activation='relu', padding='same'), + layers.GlobalAveragePooling2D(), + layers.Dense(y_test.shape[-1], activation='softmax') + ]) + model.compile(loss='categorical_crossentropy', + optimizer='rmsprop', + metrics=['accuracy']) + history = model.fit_generator(img_gen.flow(x_train, y_train, batch_size=16), + epochs=10, + validation_data=img_gen.flow(x_test, y_test, + batch_size=16), + verbose=0) + assert history.history['val_acc'][-1] > 0.75 + model.evaluate_generator(img_gen.flow(x_train, y_train, batch_size=16)) + + if __name__ == '__main__': pytest.main([__file__])
============================= test session starts ============================== platform linux -- Python 3.7.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python cachedir: .pytest_cache rootdir: /home/user/BugsInPy/temp/projects/keras, inifile: pytest.ini plugins: forked-1.1.3, flaky-3.6.1, xdist-1.32.0 gw0 I / gw1 I [gw0] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] linux Python 3.7.3 cwd: /home/user/BugsInPy/temp/projects/keras [gw1] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] [gw0] Python 3.7.3 (default, Mar 27 2019, 22:11:17) -- [GCC 7.3.0] gw0 [1] / gw1 [1] scheduling tests via LoadScheduling tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training [gw1] [100%] FAILED tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training =================================== FAILURES =================================== ______________________ test_image_data_generator_training ______________________ [gw1] linux -- Python 3.7.3 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/bin/python def test_image_data_generator_training(): np.random.seed(1337) img_gen = ImageDataGenerator(rescale=1.) # Dummy ImageDataGenerator input_shape = (16, 16, 3) (x_train, y_train), (x_test, y_test) = get_test_data(num_train=500, num_test=200, input_shape=input_shape, classification=True, num_classes=4) y_train = to_categorical(y_train) y_test = to_categorical(y_test) model = Sequential([ layers.Conv2D(filters=8, kernel_size=3, activation='relu', input_shape=input_shape), layers.MaxPooling2D(pool_size=2), layers.Conv2D(filters=4, kernel_size=(3, 3), activation='relu', padding='same'), layers.GlobalAveragePooling2D(), layers.Dense(y_test.shape[-1], activation='softmax') ]) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) history = model.fit_generator(img_gen.flow(x_train, y_train, batch_size=16), epochs=10, validation_data=img_gen.flow(x_test, y_test, batch_size=16), > verbose=0) tests/integration_tests/test_image_data_tasks.py:74: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ keras/legacy/interfaces.py:91: in wrapper return func(*args, **kwargs) keras/engine/training.py:1418: in fit_generator initial_epoch=initial_epoch) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ model = <keras.engine.sequential.Sequential object at 0x7fd8840a5fd0> generator = <keras_preprocessing.image.numpy_array_iterator.NumpyArrayIterator object at 0x7fd88409ca58> steps_per_epoch = None, epochs = 10, verbose = 0, callbacks = None validation_data = <keras_preprocessing.image.numpy_array_iterator.NumpyArrayIterator object at 0x7fd8840b63c8> validation_steps = None, class_weight = None, max_queue_size = 10, workers = 1 use_multiprocessing = False, shuffle = True, initial_epoch = 0 def fit_generator(model, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0): """See docstring for `Model.fit_generator`.""" epoch = initial_epoch do_validation = bool(validation_data) model._make_train_function() if do_validation: model._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps_per_epoch is None: if is_sequence: steps_per_epoch = len(generator) else: > raise ValueError('`steps_per_epoch=None` is only valid for a' ' generator based on the ' '`keras.utils.Sequence`' ' class. Please specify `steps_per_epoch` ' 'or use the `keras.utils.Sequence` class.') E ValueError: `steps_per_epoch=None` is only valid for a generator based on the `keras.utils.Sequence` class. Please specify `steps_per_epoch` or use the `keras.utils.Sequence` class. keras/engine/training_generator.py:54: ValueError ----------------------------- Captured stderr call ----------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4140: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3978: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3297: The name tf.log is deprecated. Please use tf.math.log instead. WARNING:tensorflow:From /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2743: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. ------------------------------ Captured log call ------------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:4140: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3978: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:3297: The name tf.log is deprecated. Please use tf.math.log instead. WARNING tensorflow:deprecation.py:323 From /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:2743: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. --------------------------- Captured stderr teardown --------------------------- WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING:tensorflow:From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. ---------------------------- Captured log teardown ----------------------------- WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead. WARNING tensorflow:module_wrapper.py:139 From /home/user/BugsInPy/temp/projects/keras/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead. =============================== warnings summary =============================== keras/preprocessing/image.py:440 /home/user/BugsInPy/temp/projects/keras/keras/preprocessing/image.py:440: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec() image.ImageDataGenerator.__init__).args: /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/tensor_util.py:521: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. tensor_proto.tensor_content = nparray.tostring() /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:339: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if not isinstance(values, collections.Sequence): /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26 /opt/conda/envs/ec1239e90de2b89d455019719a3688a0/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/learn_io/generator_io.py:26: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Container -- Docs: https://docs.pytest.org/en/latest/warnings.html ========================== slowest 20 test durations =========================== 0.69s call tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training 0.01s teardown tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training (0.00 durations hidden. Use -vv to show these durations.) =========================== short test summary info ============================ FAILED tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training ======================== 1 failed, 7 warnings in 11.38s ======================== Using TensorFlow backend.
pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training
36b9e4c055f32718a036cabaf767325b010c7485
tests/integration_tests/test_image_data_tasks.py