From 07191cedde8cc3ff21d789431aa45d33226a56b2 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 25 Jun 2019 14:06:42 -0400 Subject: [PATCH 01/24] add zuul configuration --- zuul.yaml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 zuul.yaml diff --git a/zuul.yaml b/zuul.yaml new file mode 100644 index 00000000..6efa44f2 --- /dev/null +++ b/zuul.yaml @@ -0,0 +1,5 @@ +- project: + templates: + - wazo-integrations + - wazo-py35 + - wazo-linters From 59c1e66f8ab0c1bac0ca0295adaf22908b4d98c2 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 28 Jun 2019 14:50:47 -0400 Subject: [PATCH 02/24] zuul: remove integration tests one step at a time to be able to see some progress --- zuul.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/zuul.yaml b/zuul.yaml index 6efa44f2..07796155 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -1,5 +1,4 @@ - project: templates: - - wazo-integrations - wazo-py35 - wazo-linters From e3f402756bf056035847985d690ee5a98117f939 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 28 Jun 2019 14:51:14 -0400 Subject: [PATCH 03/24] gitignore: add python related files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index efc4c0d0..da1646ed 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ cover/ coverage.xml pylint.txt unit-tests.xml +pycodestyle.txt From ec356001f4f09af2f2d4c5617b7c98dcb71e96d3 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 28 Jun 2019 14:53:24 -0400 Subject: [PATCH 04/24] zuul config: update template names --- zuul.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zuul.yaml b/zuul.yaml index 07796155..8c36eafe 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -1,4 +1,4 @@ - project: templates: - - wazo-py35 - - wazo-linters + - wazo-tox-py35 + - wazo-tox-linters From cfbc14f350cf37a457dd6fe2e7eb31c1f3644334 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 5 Jul 2019 14:13:08 -0400 Subject: [PATCH 05/24] zuul: start with the linter only --- zuul.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/zuul.yaml b/zuul.yaml index 8c36eafe..faa20531 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -1,4 +1,3 @@ - project: templates: - - wazo-tox-py35 - wazo-tox-linters From 25b3d9e3ca4f84d8f50a5f1b2fcc2d92098cc2cb Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 5 Jul 2019 14:23:02 -0400 Subject: [PATCH 06/24] tox: add the linters section --- tox.ini | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tox.ini b/tox.ini index 47756643..735bf27f 100644 --- a/tox.ini +++ b/tox.ini @@ -35,3 +35,15 @@ deps = pylint whitelist_externals = sh + +[testenv:linters] +skip_install = true +basepython = python3 +deps = flake8 + flake8-colors + black +commands = + # do not fail for black + -black --skip-string-normalization --check . + flake8 + From 0bbd7b5ce2a535f4e932b2fea151ae273ed937bd Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Fri, 5 Jul 2019 17:01:16 -0400 Subject: [PATCH 07/24] fix flake8 errors for the tox linter --- ...dd_the_hash_column_on_the_contact_table.py | 6 +- ...88fa7_remove_duplicate_contact_field_id.py | 23 ++++--- ...352_allow_contacts_to_be_in_a_phonebook.py | 6 +- .../265d68f9c337_add_contact_relation.py | 19 ++++-- ...ed2_add_tables_for_the_phonebook_plugin.py | 22 +++--- ...4e25_add_tables_for_the_favorite_plugin.py | 22 ++++-- .../38485dfa4e41_add_the_fields_table.py | 13 ++-- ...41a847a26_make_contact_key_a_text_field.py | 6 +- .../b0df0bc0ce37_add_the_contact_table.py | 14 ++-- .../d237d33088c6_add_the_user_table.py | 8 +-- .../suite/test_authentication.py | 4 +- .../suite/test_conference_contacts.py | 4 +- .../suite/test_conference_http.py | 4 +- .../suite/test_core_functionality.py | 1 - integration_tests/suite/test_csv_http.py | 4 +- integration_tests/suite/test_csv_ws_http.py | 4 +- integration_tests/suite/test_database.py | 20 ++++-- integration_tests/suite/test_displays.py | 24 +++++-- integration_tests/suite/test_ldap_http.py | 4 +- integration_tests/suite/test_personal.py | 10 ++- integration_tests/suite/test_personal_http.py | 4 +- integration_tests/suite/test_phone_view.py | 68 ++++++++++++++----- .../suite/test_phonebook_http.py | 8 ++- integration_tests/suite/test_profiles.py | 41 ++++++++--- integration_tests/suite/test_sources.py | 4 +- .../suite/test_wazo_user_contacts.py | 4 +- .../suite/test_wazo_user_http.py | 4 +- setup.py | 4 +- wazo_dird/config.py | 4 +- wazo_dird/database/models.py | 10 ++- wazo_dird/database/queries/personal.py | 2 + wazo_dird/database/queries/phonebook.py | 1 - wazo_dird/database/queries/source.py | 4 +- wazo_dird/plugins/api/http.py | 11 ++- wazo_dird/plugins/backends/service.py | 4 +- wazo_dird/plugins/base_plugins.py | 3 +- wazo_dird/plugins/config/plugin.py | 6 +- wazo_dird/plugins/config_service/plugin.py | 7 +- .../csv_backend/tests/test_csv_plugin.py | 10 ++- wazo_dird/plugins/csv_ws_backend/plugin.py | 12 +++- .../csv_ws_backend/tests/test_csv_ws.py | 10 ++- .../tests/test_default_json_view.py | 8 ++- wazo_dird/plugins/favorites_service/plugin.py | 5 +- wazo_dird/plugins/ldap_backend/plugin.py | 49 +++++++++---- wazo_dird/plugins/ldap_backend/schemas.py | 4 +- .../ldap_backend/tests/test_ldap_plugin.py | 24 +++++-- wazo_dird/plugins/personal_service/plugin.py | 8 ++- wazo_dird/plugins/phone/http.py | 13 +++- .../plugins/phone/tests/test_phone_view.py | 10 ++- wazo_dird/plugins/phone_helpers.py | 12 +++- wazo_dird/plugins/phonebook/http.py | 28 ++++---- wazo_dird/plugins/phonebook/plugin.py | 36 +++++++--- .../plugins/phonebook_backend/schemas.py | 1 - .../tests/test_phonebook_service.py | 26 +++++-- wazo_dird/plugins/profile_sources/plugin.py | 6 +- wazo_dird/plugins/profiles/http.py | 5 +- wazo_dird/plugins/reverse_service/plugin.py | 4 +- wazo_dird/plugins/sample_backend/plugin.py | 22 +++--- .../tests/test_sample_backend.py | 8 ++- wazo_dird/plugins/source_result.py | 22 ++++-- wazo_dird/rest_api.py | 9 ++- wazo_dird/service_discovery.py | 5 +- wazo_dird/source_manager.py | 7 +- wazo_dird/tests/test_config.py | 2 +- wazo_dird/tests/test_controller.py | 4 +- wazo_dird/tests/test_main.py | 8 ++- 66 files changed, 529 insertions(+), 236 deletions(-) diff --git a/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py b/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py index f6ab720c..6a41e57a 100644 --- a/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py +++ b/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py @@ -5,13 +5,13 @@ """ +from alembic import op +import sqlalchemy as sa + # revision identifiers, used by Alembic. revision = '1c6344eac1bd' down_revision = '38485dfa4e41' -from alembic import op -import sqlalchemy as sa - constraint_name = 'dird_contact_hash_user_uuid' table_name = 'dird_contact' column_name = 'hash' diff --git a/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py b/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py index b3da07d4..974a395f 100644 --- a/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py +++ b/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py @@ -5,14 +5,13 @@ """ +from alembic import op +from sqlalchemy import sql + # revision identifiers, used by Alembic. revision = '1e0397088fa7' down_revision = '1e66a71e0352' -import sqlalchemy as sa -from alembic import op -from sqlalchemy import sql - contact_field_table = sql.table('dird_contact_fields', sql.column('id'), sql.column('name'), @@ -27,20 +26,26 @@ def upgrade(): if id_contact_field_row.contact_uuid not in known_contact_ids: known_contact_ids.add(id_contact_field_row.contact_uuid) else: - query = contact_field_table.delete().where(contact_field_table.c.id == id_contact_field_row.id) + query = contact_field_table.delete().where( + contact_field_table.c.id == id_contact_field_row.id + ) op.get_bind().execute(query) def purge_divergent_id_contact_fields(): - query = contact_field_table.delete().where(sql.and_(contact_field_table.c.name == 'id', - contact_field_table.c.value != contact_field_table.c.contact_uuid)) + query = contact_field_table.delete().where(sql.and_( + contact_field_table.c.name == 'id', + contact_field_table.c.value != contact_field_table.c.contact_uuid, + )) op.get_bind().execute(query) def get_id_contact_field_rows(): id_contact_fields = (sql.select([contact_field_table.c.id, contact_field_table.c.contact_uuid]) - .where(sql.and_(contact_field_table.c.name == 'id', - contact_field_table.c.value == contact_field_table.c.contact_uuid))) + .where(sql.and_( + contact_field_table.c.name == 'id', + contact_field_table.c.value == contact_field_table.c.contact_uuid, + ))) return op.get_bind().execute(id_contact_fields) diff --git a/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py b/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py index ae72f908..7e840c6b 100644 --- a/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py +++ b/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py @@ -5,13 +5,13 @@ """ +from alembic import op +import sqlalchemy as sa + # revision identifiers, used by Alembic. revision = '1e66a71e0352' down_revision = '28e9ff92ed2' -from alembic import op -import sqlalchemy as sa - constraint_name = 'dird_contact_hash_phonebook_id' table_name = 'dird_contact' diff --git a/alembic/versions/265d68f9c337_add_contact_relation.py b/alembic/versions/265d68f9c337_add_contact_relation.py index db087456..99e531d8 100644 --- a/alembic/versions/265d68f9c337_add_contact_relation.py +++ b/alembic/versions/265d68f9c337_add_contact_relation.py @@ -5,22 +5,27 @@ """ +from alembic import op +import sqlalchemy as sa + # revision identifiers, used by Alembic. revision = '265d68f9c337' down_revision = 'd237d33088c6' -from alembic import op -import sqlalchemy as sa - table_name = 'dird_contact' column_name = 'user_uuid' def upgrade(): - op.add_column(table_name, sa.Column(column_name, - sa.String(38), - sa.ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), - nullable=False)) + op.add_column( + table_name, + sa.Column( + column_name, + sa.String(38), + sa.ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), + nullable=False, + ) + ) def downgrade(): diff --git a/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py b/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py index 000cf5a5..14ef75c9 100644 --- a/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py +++ b/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py @@ -5,19 +5,21 @@ """ -# revision identifiers, used by Alembic. -revision = '28e9ff92ed2' -down_revision = '2caf42314e25' - from alembic import op from sqlalchemy.schema import Column -from sqlalchemy import (CheckConstraint, - ForeignKey, - Integer, - String, - Text, - UniqueConstraint) +from sqlalchemy import ( + CheckConstraint, + ForeignKey, + Integer, + String, + Text, + UniqueConstraint, +) + +# revision identifiers, used by Alembic. +revision = '28e9ff92ed2' +down_revision = '2caf42314e25' def upgrade(): diff --git a/alembic/versions/2caf42314e25_add_tables_for_the_favorite_plugin.py b/alembic/versions/2caf42314e25_add_tables_for_the_favorite_plugin.py index 75695ca2..c816a2ce 100644 --- a/alembic/versions/2caf42314e25_add_tables_for_the_favorite_plugin.py +++ b/alembic/versions/2caf42314e25_add_tables_for_the_favorite_plugin.py @@ -5,15 +5,15 @@ """ -# revision identifiers, used by Alembic. -revision = '2caf42314e25' -down_revision = '4cf41a847a26' - from alembic import op from sqlalchemy.schema import Column from sqlalchemy import ForeignKey, String, Text, Integer +# revision identifiers, used by Alembic. +revision = '2caf42314e25' +down_revision = '4cf41a847a26' + def upgrade(): op.create_table( @@ -23,9 +23,19 @@ def upgrade(): ) op.create_table( 'dird_favorite', - Column('source_id', Integer(), ForeignKey('dird_source.id', ondelete='CASCADE'), primary_key=True), + Column( + 'source_id', + Integer(), + ForeignKey('dird_source.id', ondelete='CASCADE'), + primary_key=True, + ), Column('contact_id', Text(), primary_key=True), - Column('user_uuid', String(38), ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), primary_key=True), + Column( + 'user_uuid', + String(38), + ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), + primary_key=True, + ), ) diff --git a/alembic/versions/38485dfa4e41_add_the_fields_table.py b/alembic/versions/38485dfa4e41_add_the_fields_table.py index c75c3bd7..c40766d3 100644 --- a/alembic/versions/38485dfa4e41_add_the_fields_table.py +++ b/alembic/versions/38485dfa4e41_add_the_fields_table.py @@ -5,13 +5,13 @@ """ +from alembic import op +from sqlalchemy import Column, String, Text, Integer, ForeignKey + # revision identifiers, used by Alembic. revision = '38485dfa4e41' down_revision = '265d68f9c337' -from alembic import op -from sqlalchemy import Column, String, Text, Integer, ForeignKey - table_name = 'dird_contact_fields' name_index = '{}_name_idx'.format(table_name) value_index = '{}_value_idx'.format(table_name) @@ -23,7 +23,12 @@ def upgrade(): Column('id', Integer, primary_key=True), Column('name', String(20), nullable=False, index=True), Column('value', Text(), index=True), - Column('contact_uuid', String(38), ForeignKey('dird_contact.uuid', ondelete='CASCADE'), nullable=False), + Column( + 'contact_uuid', + String(38), + ForeignKey('dird_contact.uuid', ondelete='CASCADE'), + nullable=False, + ), ) diff --git a/alembic/versions/4cf41a847a26_make_contact_key_a_text_field.py b/alembic/versions/4cf41a847a26_make_contact_key_a_text_field.py index e015e8c4..d07e2f5e 100644 --- a/alembic/versions/4cf41a847a26_make_contact_key_a_text_field.py +++ b/alembic/versions/4cf41a847a26_make_contact_key_a_text_field.py @@ -5,13 +5,13 @@ """ +from alembic import op +from sqlalchemy.types import Text, String + # revision identifiers, used by Alembic. revision = '4cf41a847a26' down_revision = '1c6344eac1bd' -from alembic import op -from sqlalchemy.types import Text, String - def upgrade(): _change_type(Text) diff --git a/alembic/versions/b0df0bc0ce37_add_the_contact_table.py b/alembic/versions/b0df0bc0ce37_add_the_contact_table.py index 0f543115..47112eca 100644 --- a/alembic/versions/b0df0bc0ce37_add_the_contact_table.py +++ b/alembic/versions/b0df0bc0ce37_add_the_contact_table.py @@ -5,20 +5,22 @@ """ -# revision identifiers, used by Alembic. -revision = 'b0df0bc0ce37' -down_revision = None - from alembic import op from sqlalchemy.schema import Column from sqlalchemy import String, text +# revision identifiers, used by Alembic. +revision = 'b0df0bc0ce37' +down_revision = None + table_name = 'dird_contact' def upgrade(): - op.create_table(table_name, - Column('uuid', String(38), server_default=text('uuid_generate_v4()'), primary_key=True)) + op.create_table( + table_name, + Column('uuid', String(38), server_default=text('uuid_generate_v4()'), primary_key=True), + ) def downgrade(): diff --git a/alembic/versions/d237d33088c6_add_the_user_table.py b/alembic/versions/d237d33088c6_add_the_user_table.py index e3d8c8d2..27136ee2 100644 --- a/alembic/versions/d237d33088c6_add_the_user_table.py +++ b/alembic/versions/d237d33088c6_add_the_user_table.py @@ -5,14 +5,14 @@ """ -# revision identifiers, used by Alembic. -revision = 'd237d33088c6' -down_revision = 'b0df0bc0ce37' - from alembic import op from sqlalchemy.schema import Column from sqlalchemy import String +# revision identifiers, used by Alembic. +revision = 'd237d33088c6' +down_revision = 'b0df0bc0ce37' + table_name = 'dird_user' diff --git a/integration_tests/suite/test_authentication.py b/integration_tests/suite/test_authentication.py index 5fa22d76..8b3da3b7 100644 --- a/integration_tests/suite/test_authentication.py +++ b/integration_tests/suite/test_authentication.py @@ -49,7 +49,9 @@ def test_no_auth_server_gives_503(self): result = self.get_headers_result('default', token=VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(503)) - assert_that(result.json()['reason'][0], contains_string('Authentication server unreachable')) + assert_that(result.json()['reason'][0], contains_string( + 'Authentication server unreachable', + )) class TestAuthenticationCoverage(BaseDirdIntegrationTest): diff --git a/integration_tests/suite/test_conference_contacts.py b/integration_tests/suite/test_conference_contacts.py index c1bb3ca4..520a24ad 100644 --- a/integration_tests/suite/test_conference_contacts.py +++ b/integration_tests/suite/test_conference_contacts.py @@ -73,7 +73,9 @@ def test_with_no_confd(self): try: assert_that( calling(self.contacts).with_args(self.client, self.source_uuid), - raises(Exception).matching(has_properties(response=has_properties(status_code=503))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=503), + )) ) finally: self.start_service('america') diff --git a/integration_tests/suite/test_conference_http.py b/integration_tests/suite/test_conference_http.py index f75ed37b..949bb864 100644 --- a/integration_tests/suite/test_conference_http.py +++ b/integration_tests/suite/test_conference_http.py @@ -299,7 +299,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.conference_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): diff --git a/integration_tests/suite/test_core_functionality.py b/integration_tests/suite/test_core_functionality.py index 0ac666b4..a34e9d5d 100644 --- a/integration_tests/suite/test_core_functionality.py +++ b/integration_tests/suite/test_core_functionality.py @@ -9,7 +9,6 @@ contains_inanyorder, contains_string, equal_to, - has_item, has_length, has_entries, ) diff --git a/integration_tests/suite/test_csv_http.py b/integration_tests/suite/test_csv_http.py index 3b1478a3..8abb570a 100644 --- a/integration_tests/suite/test_csv_http.py +++ b/integration_tests/suite/test_csv_http.py @@ -261,7 +261,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.csv_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): diff --git a/integration_tests/suite/test_csv_ws_http.py b/integration_tests/suite/test_csv_ws_http.py index ca15b782..78915a3a 100644 --- a/integration_tests/suite/test_csv_ws_http.py +++ b/integration_tests/suite/test_csv_ws_http.py @@ -253,7 +253,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.csv_ws_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): diff --git a/integration_tests/suite/test_database.py b/integration_tests/suite/test_database.py index d5c46a10..1075f24b 100644 --- a/integration_tests/suite/test_database.py +++ b/integration_tests/suite/test_database.py @@ -48,6 +48,7 @@ def new_uuid(): return str(uuid4()) + TENANT_UUID = new_uuid() @@ -950,7 +951,11 @@ def test_that_personal_contacts_remain_unique(self, xivo_user_uuid): @with_user_uuid @with_user_uuid - def test_that_personal_contacts_can_be_duplicated_between_users(self, user_uuid_1, user_uuid_2): + def test_that_personal_contacts_can_be_duplicated_between_users( + self, + user_uuid_1, + user_uuid_2, + ): contact_1_uuid = self._crud.create_personal_contact(user_uuid_1, self.contact_1)['id'] contact_2_uuid = self._crud.create_personal_contact(user_uuid_2, self.contact_1)['id'] @@ -1249,7 +1254,10 @@ def test_that_listing_personal_contacts_returns_the_searched_contacts(self, xivo ids = self._insert_personal_contacts(xivo_user_uuid, self.contact_1, self.contact_2) result = engine.list_personal_contacts(xivo_user_uuid, ids) - assert_that(result, contains_inanyorder(expected(self.contact_1), expected(self.contact_2))) + assert_that(result, contains_inanyorder( + expected(self.contact_1), + expected(self.contact_2), + )) result = engine.list_personal_contacts(xivo_user_uuid, ids[:1]) assert_that(result, contains(expected(self.contact_1))) @@ -1266,10 +1274,14 @@ def test_that_listing_personal_contacts_only_the_users_contact(self, uuid_1, uui ids_2 = self._insert_personal_contacts(uuid_2, self.contact_1, self.contact_3) result = engine.list_personal_contacts(uuid_1, ids_1) - assert_that(result, contains_inanyorder(expected(self.contact_1), expected(self.contact_2))) + assert_that(result, contains_inanyorder( + expected(self.contact_1), expected(self.contact_2))) result = engine.list_personal_contacts(uuid_2, ids_2) - assert_that(result, contains_inanyorder(expected(self.contact_1), expected(self.contact_3))) + assert_that(result, contains_inanyorder( + expected(self.contact_1), + expected(self.contact_3), + )) result = engine.list_personal_contacts(uuid_1, ids_2) assert_that(result, empty()) diff --git a/integration_tests/suite/test_displays.py b/integration_tests/suite/test_displays.py index 95133cee..7d70f269 100644 --- a/integration_tests/suite/test_displays.py +++ b/integration_tests/suite/test_displays.py @@ -57,12 +57,16 @@ def test_multi_tenant(self, sub, main): ) assert_that( - calling(main_tenant_client.displays.delete).with_args(main['uuid'], tenant_uuid=SUB_TENANT), + calling(main_tenant_client.displays.delete).with_args( + main['uuid'], tenant_uuid=SUB_TENANT + ), raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) assert_that( - calling(sub_tenant_client.displays.delete).with_args(main['uuid'], tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.displays.delete).with_args( + main['uuid'], tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) @@ -94,7 +98,9 @@ def test_multi_tenant(self, sub, main): assert_that(response, equal_to(sub)) assert_that( - calling(main_tenant_client.displays.get).with_args(main['uuid'], tenant_uuid=SUB_TENANT), + calling(main_tenant_client.displays.get).with_args( + main['uuid'], tenant_uuid=SUB_TENANT + ), raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) @@ -104,7 +110,9 @@ def test_multi_tenant(self, sub, main): ) assert_that( - calling(sub_tenant_client.displays.get).with_args(main['uuid'], tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.displays.get).with_args( + main['uuid'], tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) @@ -346,12 +354,16 @@ def test_put_multi_tenant(self, sub, main): ) assert_that( - calling(sub_tenant_client.displays.edit).with_args(main['uuid'], self.valid_body, tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.displays.edit).with_args( + main['uuid'], self.valid_body, tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) assert_that( - calling(main_tenant_client.displays.edit).with_args(main['uuid'], self.valid_body, tenant_uuid=SUB_TENANT), + calling(main_tenant_client.displays.edit).with_args( + main['uuid'], self.valid_body, tenant_uuid=SUB_TENANT, + ), raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) diff --git a/integration_tests/suite/test_ldap_http.py b/integration_tests/suite/test_ldap_http.py index 8adf7ad0..76961fd0 100644 --- a/integration_tests/suite/test_ldap_http.py +++ b/integration_tests/suite/test_ldap_http.py @@ -259,7 +259,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.ldap_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): diff --git a/integration_tests/suite/test_personal.py b/integration_tests/suite/test_personal.py index 29e4804e..7f15c09b 100644 --- a/integration_tests/suite/test_personal.py +++ b/integration_tests/suite/test_personal.py @@ -346,7 +346,11 @@ def test_that_edit_personal_contact_replaces_attributes(self): def test_that_edit_cannot_duplicate_contacts(self): contact_1 = self.post_personal({'firstname': 'Noémie', 'lastname': 'Narvidon'}) self.post_personal({'firstname': 'Paul', 'lastname': 'Narvidon'}) - put_result = self.put_personal_result(contact_1['id'], {'firstname': 'Paul', 'lastname': 'Narvidon'}, VALID_TOKEN_MAIN_TENANT) + put_result = self.put_personal_result( + contact_1['id'], + {'firstname': 'Paul', 'lastname': 'Narvidon'}, + VALID_TOKEN_MAIN_TENANT, + ) assert_that(put_result.status_code, equal_to(409)) list_result = self.list_personal() @@ -386,7 +390,9 @@ def test_that_get_returns_all_attributes(self): })) def test_that_personal_api_is_symmetric(self): - contact_post = self.post_personal({'firstname': 'Noémie', 'lastname': 'Narvidon', 'special-key': ''}) + contact_post = self.post_personal( + {'firstname': 'Noémie', 'lastname': 'Narvidon', 'special-key': ''}, + ) contact_put = self.put_personal(contact_post['id'], contact_post) contact_get = self.get_personal(contact_post['id']) diff --git a/integration_tests/suite/test_personal_http.py b/integration_tests/suite/test_personal_http.py index dc333e71..dbaae0ec 100644 --- a/integration_tests/suite/test_personal_http.py +++ b/integration_tests/suite/test_personal_http.py @@ -256,7 +256,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.personal_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): diff --git a/integration_tests/suite/test_phone_view.py b/integration_tests/suite/test_phone_view.py index 2c8884be..1532593f 100644 --- a/integration_tests/suite/test_phone_view.py +++ b/integration_tests/suite/test_phone_view.py @@ -27,11 +27,15 @@ class TestPhoneView(BaseDirdIntegrationTest): config_factory = new_phone_view_config def test_given_invalid_offset_then_lookup_return_400(self): - result = self.get_lookup_cisco_result(self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, offset=-1) + result = self.get_lookup_cisco_result( + self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, offset=-1, + ) assert_that(result.status_code, equal_to((400))) def test_given_invalid_limit_then_lookup_return_400(self): - result = self.get_lookup_cisco_result(self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, limit=-1) + result = self.get_lookup_cisco_result( + self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, limit=-1 + ) assert_that(result.status_code, equal_to((400))) def test_that_dird_replace_url_by_proxy(self): @@ -93,63 +97,93 @@ def test_that_lookup_return_result(self): assert_that(result, contains_string('5555555555')) def test_that_lookup_return_400_when_no_term(self): - result = self.get_lookup_cisco_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_cisco_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to(400)) def test_that_lookup_return_404_when_unknown_profile(self): - result = self.get_lookup_cisco_result('quiproquo', VALID_UUID, term='alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_cisco_result( + 'quiproquo', VALID_UUID, term='alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to(404)) def test_aastra_input_route(self): - result = self.get_input_aastra_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_aastra_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_aastra_lookup_route(self): - result = self.get_lookup_aastra_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_aastra_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_cisco_input_route(self): - result = self.get_input_cisco_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_cisco_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_cisco_menu_route(self): - result = self.get_menu_cisco_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_menu_cisco_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_cisco_lookup_route(self): - result = self.get_lookup_cisco_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_cisco_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_polycom_input_route(self): - result = self.get_input_polycom_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_polycom_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_polycom_lookup_route(self): - result = self.get_lookup_polycom_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_polycom_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_snom_input_route(self): - result = self.get_input_snom_result(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_snom_result( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_snom_lookup_route(self): - result = self.get_lookup_snom_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_snom_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_thomson_lookup_route(self): - result = self.get_lookup_thomson_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_thomson_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_yealink_lookup_route(self): - result = self.get_lookup_yealink_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_yealink_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_gigaset_lookup_route(self): - result = self.get_lookup_gigaset_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_gigaset_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) def test_htek_lookup_route(self): - result = self.get_lookup_htek_result(self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_htek_result( + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + ) assert_that(result.status_code, equal_to((200))) diff --git a/integration_tests/suite/test_phonebook_http.py b/integration_tests/suite/test_phonebook_http.py index 6a287c1e..08b6a3c4 100644 --- a/integration_tests/suite/test_phonebook_http.py +++ b/integration_tests/suite/test_phonebook_http.py @@ -242,7 +242,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.phonebook_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=409), + )) ) def test_multi_tenant(self): @@ -351,7 +353,9 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.phonebook_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.phonebook_source.edit).with_args( + sub['uuid'], self.new_body, + ), not_(raises(Exception)), ) diff --git a/integration_tests/suite/test_profiles.py b/integration_tests/suite/test_profiles.py index 4cde4981..72e31c37 100644 --- a/integration_tests/suite/test_profiles.py +++ b/integration_tests/suite/test_profiles.py @@ -13,7 +13,6 @@ equal_to, has_entries, has_properties, - is_, not_, ) from xivo_test_helpers.hamcrest.raises import raises @@ -95,14 +94,18 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): ) assert_that( - calling(sub_tenant_client.profiles.delete).with_args(profile['uuid'], tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.profiles.delete).with_args( + profile['uuid'], tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=401)), ), ) assert_that( - calling(main_tenant_client.profiles.delete).with_args(profile['uuid'], tenant_uuid=SUB_TENANT), + calling(main_tenant_client.profiles.delete).with_args( + profile['uuid'], tenant_uuid=SUB_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=404)), ), @@ -161,14 +164,18 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): ) assert_that( - calling(main_tenant_client.profiles.get).with_args(profile['uuid'], tenant_uuid=SUB_TENANT), + calling(main_tenant_client.profiles.get).with_args( + profile['uuid'], tenant_uuid=SUB_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=404)), ), ) assert_that( - calling(sub_tenant_client.profiles.get).with_args(profile['uuid'], tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.profiles.get).with_args( + profile['uuid'], tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=401)), ), @@ -198,7 +205,9 @@ def test_search(self, source, display): self.profile(self.client, body_bcd) as bcd, \ self.profile(self.client, body_cde) as cde: result = self.client.profiles.list() - self.assert_list_result(result, contains_inanyorder(abc, bcd, cde), total=3, filtered=3) + self.assert_list_result( + result, contains_inanyorder(abc, bcd, cde), total=3, filtered=3, + ) result = self.client.profiles.list(name='abc') self.assert_list_result(result, contains(abc), total=3, filtered=1) @@ -270,7 +279,9 @@ def test_multi_tenant(self, sub_source, main_source, sub_display, main_display): assert_that( calling(sub_tenant_client.profiles.list).with_args(tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=401), + )) ) @@ -492,14 +503,18 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): ) assert_that( - calling(main_tenant_client.profiles.edit).with_args(profile['uuid'], body, tenant_uuid=SUB_TENANT), + calling(main_tenant_client.profiles.edit).with_args( + profile['uuid'], body, tenant_uuid=SUB_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=404)), ), ) assert_that( - calling(sub_tenant_client.profiles.edit).with_args(profile['uuid'], body, tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.profiles.edit).with_args( + profile['uuid'], body, tenant_uuid=MAIN_TENANT, + ), raises(Exception).matching( has_properties(response=has_properties(status_code=401)), ), @@ -655,7 +670,9 @@ def test_given_random_order_when_get_then_bad_request(self): def test_given_wrong_tenant_when_get_then_not_found(self): assert_that( - calling(self.client.directories.list_sources).with_args('main', tenant_uuid=SUB_TENANT), + calling(self.client.directories.list_sources).with_args( + 'main', tenant_uuid=SUB_TENANT, + ), raises(HTTPError).matching( has_properties(response=has_properties(status_code=404)), ), @@ -670,7 +687,9 @@ def test_given_sub_tenant_when_get_main_tenant_then_unauthorized(self): sub_tenant_client = self.get_client(VALID_TOKEN_SUB_TENANT) assert_that( - calling(sub_tenant_client.directories.list_sources).with_args('main', tenant_uuid=MAIN_TENANT), + calling(sub_tenant_client.directories.list_sources).with_args( + 'main', tenant_uuid=MAIN_TENANT, + ), raises(HTTPError).matching( has_properties(response=has_properties(status_code=401)), ), diff --git a/integration_tests/suite/test_sources.py b/integration_tests/suite/test_sources.py index c67549cf..015bc7bd 100644 --- a/integration_tests/suite/test_sources.py +++ b/integration_tests/suite/test_sources.py @@ -89,7 +89,9 @@ def test_multi_tenant(self, bcd, abc): ), total=1, filtered=1) assert_that( - calling(sub_tenant_client.sources.list).with_args(tenant_uuid=MAIN_TENANT, recurse=True), + calling(sub_tenant_client.sources.list).with_args( + tenant_uuid=MAIN_TENANT, recurse=True, + ), raises(Exception).matching(has_properties(response=has_properties(status_code=401))) ) diff --git a/integration_tests/suite/test_wazo_user_contacts.py b/integration_tests/suite/test_wazo_user_contacts.py index 7d55f32f..d671fcf5 100644 --- a/integration_tests/suite/test_wazo_user_contacts.py +++ b/integration_tests/suite/test_wazo_user_contacts.py @@ -114,7 +114,9 @@ def test_with_no_confd(self): try: assert_that( calling(self.contacts).with_args(self.client, self.source_uuid), - raises(Exception).matching(has_properties(response=has_properties(status_code=503))) + raises(Exception).matching(has_properties( + response=has_properties(status_code=503), + )) ) finally: self.start_service('america') diff --git a/integration_tests/suite/test_wazo_user_http.py b/integration_tests/suite/test_wazo_user_http.py index f1e2fcb3..7cbc2139 100644 --- a/integration_tests/suite/test_wazo_user_http.py +++ b/integration_tests/suite/test_wazo_user_http.py @@ -260,7 +260,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.wazo_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)), + ) ) def test_multi_tenant(self): diff --git a/setup.py b/setup.py index de7fb6f0..9de335b3 100755 --- a/setup.py +++ b/setup.py @@ -69,7 +69,7 @@ def babel(self): 'phonebook = wazo_dird.plugins.phonebook_service.plugin:PhonebookServicePlugin', 'profile = wazo_dird.plugins.profile_service.plugin:ProfileServicePlugin', 'reverse = wazo_dird.plugins.reverse_service.plugin:ReverseServicePlugin', - 'service_discovery = wazo_dird.plugins.service_discovery_service.plugin:ServiceDiscoveryServicePlugin', + 'service_discovery = wazo_dird.plugins.service_discovery_service.plugin:ServiceDiscoveryServicePlugin', # noqa 'source = wazo_dird.plugins.source_service.plugin:SourceServicePlugin', ], 'wazo_dird.backends': [ @@ -98,7 +98,7 @@ def babel(self): 'phonebook_view = wazo_dird.plugins.phonebook.plugin:PhonebookViewPlugin', 'phonebook_backend = wazo_dird.plugins.phonebook_backend.plugin:PhonebookView', 'status_view = wazo_dird.plugins.status.plugin:StatusViewPlugin', - 'tenant_migration = wazo_dird.plugins.phonebook_tenant_modifier.plugin:PhonebookTenantMoverPlugin', + 'tenant_migration = wazo_dird.plugins.phonebook_tenant_modifier.plugin:PhonebookTenantMoverPlugin', # noqa 'aastra_view = wazo_dird.plugins.aastra.plugin:AastraViewPlugin', 'cisco_view = wazo_dird.plugins.cisco.plugin:CiscoViewPlugin', 'gigaset_view = wazo_dird.plugins.gigaset.plugin:GigasetViewPlugin', diff --git a/wazo_dird/config.py b/wazo_dird/config.py index 9b188759..8cbc580b 100644 --- a/wazo_dird/config.py +++ b/wazo_dird/config.py @@ -93,7 +93,9 @@ def load(logger, argv): cli_config = _parse_cli_args(argv) file_config = read_config_file_hierarchy(ChainMap(cli_config, _DEFAULT_CONFIG)) - reinterpreted_config = _get_reinterpreted_raw_values(ChainMap(cli_config, file_config, _DEFAULT_CONFIG)) + reinterpreted_config = _get_reinterpreted_raw_values( + ChainMap(cli_config, file_config, _DEFAULT_CONFIG), + ) key_file = _load_key_file(ChainMap(cli_config, file_config, _DEFAULT_CONFIG)) return ChainMap( diff --git a/wazo_dird/database/models.py b/wazo_dird/database/models.py index 7f65429c..edea09d8 100644 --- a/wazo_dird/database/models.py +++ b/wazo_dird/database/models.py @@ -37,7 +37,9 @@ class ContactFields(Base): id = Column(Integer(), primary_key=True) name = Column(Text(), nullable=False, index=True) value = Column(Text(), index=True) - contact_uuid = Column(String(38), ForeignKey('dird_contact.uuid', ondelete='CASCADE'), nullable=False) + contact_uuid = Column( + String(38), ForeignKey('dird_contact.uuid', ondelete='CASCADE'), nullable=False, + ) class Display(Base): @@ -207,7 +209,11 @@ class Tenant(Base): __tablename__ = 'dird_tenant' - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) + uuid = Column( + String(UUID_LENGTH), + server_default=text('uuid_generate_v4()'), + primary_key=True, + ) # DEPRECATED uuids should match wazo-auth and names should not be used # the field will be removed after an upgrade that forces an upgrade above version 19.02 name = Column(String(255)) diff --git a/wazo_dird/database/queries/personal.py b/wazo_dird/database/queries/personal.py index d9c9c5a7..c18d58ed 100644 --- a/wazo_dird/database/queries/personal.py +++ b/wazo_dird/database/queries/personal.py @@ -94,6 +94,8 @@ def _new_strict_filter(self, xivo_user_uuid, term, columns): def _new_user_contacts_filter(self, xivo_user_uuid): return User.xivo_user_uuid == xivo_user_uuid + + class PersonalContactCRUD(BaseDAO): def list_personal_contacts(self, xivo_user_uuid=None): diff --git a/wazo_dird/database/queries/phonebook.py b/wazo_dird/database/queries/phonebook.py index bb562fa1..8ef96ffa 100644 --- a/wazo_dird/database/queries/phonebook.py +++ b/wazo_dird/database/queries/phonebook.py @@ -7,7 +7,6 @@ distinct, func, or_, - exc, ) from wazo_dird.exception import ( diff --git a/wazo_dird/database/queries/source.py b/wazo_dird/database/queries/source.py index 4fac3b95..5c2ba039 100644 --- a/wazo_dird/database/queries/source.py +++ b/wazo_dird/database/queries/source.py @@ -87,7 +87,9 @@ def get_by_uuid(self, uuid): return self._from_db_format(source) - def _list_filter(self, backend, visible_tenants, uuid=None, name=None, search=None, **list_params): + def _list_filter( + self, backend, visible_tenants, uuid=None, name=None, search=None, **list_params + ): filter_ = text('true') if visible_tenants is not None: filter_ = and_(filter_, Source.tenant_uuid.in_(visible_tenants)) diff --git a/wazo_dird/plugins/api/http.py b/wazo_dird/plugins/api/http.py index 2fd0f8ce..ae867fe3 100644 --- a/wazo_dird/plugins/api/http.py +++ b/wazo_dird/plugins/api/http.py @@ -35,10 +35,17 @@ def get(self): except IndexError: logger.debug('Could not find API spec from module "%s"', module.module_name) except NotImplementedError: - logger.debug('Are you sure you have an __init__ file in your module "%s"?', module.module_name) + logger.debug( + 'Are you sure you have an __init__ file in your module "%s"?', + module.module_name + ) api_spec = ChainMap(*specs) if not api_spec.get('info'): return {'error': "API spec does not exist"}, 404 - return make_response(yaml.dump(dict(api_spec)), 200, {'Content-Type': 'application/x-yaml'}) + return make_response( + yaml.dump(dict(api_spec)), + 200, + {'Content-Type': 'application/x-yaml'}, + ) diff --git a/wazo_dird/plugins/backends/service.py b/wazo_dird/plugins/backends/service.py index 209ad496..de447082 100644 --- a/wazo_dird/plugins/backends/service.py +++ b/wazo_dird/plugins/backends/service.py @@ -19,7 +19,9 @@ def __init__(self, config): installed_backends = set(module.name for module in iter_entry_points(group=self._backend_entry_points)) - self._backends = [{'name': backend} for backend in configured_backends & installed_backends] + self._backends = [ + {'name': backend} for backend in configured_backends & installed_backends + ] def list_(self, **kwargs): matches = self._filter_matches(self._backends, **kwargs) diff --git a/wazo_dird/plugins/base_plugins.py b/wazo_dird/plugins/base_plugins.py index 12d62856..763ad6e0 100644 --- a/wazo_dird/plugins/base_plugins.py +++ b/wazo_dird/plugins/base_plugins.py @@ -41,7 +41,8 @@ class BaseSourcePlugin(metaclass=abc.ABCMeta): # These string are expected in the configuration SEARCHED_COLUMNS = 'searched_columns' # These columns are the ones we search in - FIRST_MATCHED_COLUMNS = 'first_matched_columns' # These columns are the ones we search for reverse lookup + # These columns are the ones we search for reverse lookup + FIRST_MATCHED_COLUMNS = 'first_matched_columns' FORMAT_COLUMNS = 'format_columns' UNIQUE_COLUMN = 'unique_column' # This is the column that make an entry unique diff --git a/wazo_dird/plugins/config/plugin.py b/wazo_dird/plugins/config/plugin.py index be7e2710..479a7470 100644 --- a/wazo_dird/plugins/config/plugin.py +++ b/wazo_dird/plugins/config/plugin.py @@ -1,4 +1,4 @@ -# Copyright 2016-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2016-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import logging @@ -19,7 +19,9 @@ def load(self, dependencies): api = dependencies['api'] config_service = dependencies['services'].get('config') if not config_service: - logger.info('failed to load the %s config service is disabled', self.__class__.__name__) + logger.info( + 'failed to load the %s config service is disabled', self.__class__.__name__, + ) return Config.configure(config_service) diff --git a/wazo_dird/plugins/config_service/plugin.py b/wazo_dird/plugins/config_service/plugin.py index bd5d0810..ea807c28 100644 --- a/wazo_dird/plugins/config_service/plugin.py +++ b/wazo_dird/plugins/config_service/plugin.py @@ -15,7 +15,12 @@ DEFAULT_DISPLAY_COLUMNS = [ {'field': 'name', 'title': 'Nom', 'type': 'name'}, {'field': 'phone', 'title': "Num\xE9ro", 'type': 'number', 'number_display': '{name}'}, - {'field': 'phone_mobile', 'title': 'Mobile', 'type': 'number', 'number_display': '{name} (mobile)'}, + { + 'field': 'phone_mobile', + 'title': 'Mobile', + 'type': 'number', + 'number_display': '{name} (mobile)', + }, {'field': 'voicemail', 'title': "Bo\xEEte vocale", 'type': 'voicemail'}, {'field': 'favorite', 'title': 'Favoris', 'type': 'favorite'}, {'field': 'email', 'title': 'E-mail', 'type': 'email'}, diff --git a/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py b/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py index 0b13a64e..a0566b06 100644 --- a/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py +++ b/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py @@ -1,4 +1,4 @@ -# Copyright 2014-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2014-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import unittest @@ -254,11 +254,15 @@ def test_is_in_unique_ids(self): self.source.load({'config': config}) - result = self.source._is_in_unique_ids(['12'], {'firstname': 'Alice', 'lastname': 'AAA', 'clientno': '12'}) + result = self.source._is_in_unique_ids( + ['12'], {'firstname': 'Alice', 'lastname': 'AAA', 'clientno': '12'}, + ) assert_that(result, equal_to(True)) - result = self.source._is_in_unique_ids(['12'], {'firstname': 'Bob', 'lastname': 'BBB', 'clientno': '55'}) + result = self.source._is_in_unique_ids( + ['12'], {'firstname': 'Bob', 'lastname': 'BBB', 'clientno': '55'}, + ) assert_that(result, equal_to(False)) diff --git a/wazo_dird/plugins/csv_ws_backend/plugin.py b/wazo_dird/plugins/csv_ws_backend/plugin.py index 90769e41..ff6ba019 100644 --- a/wazo_dird/plugins/csv_ws_backend/plugin.py +++ b/wazo_dird/plugins/csv_ws_backend/plugin.py @@ -50,7 +50,9 @@ def search(self, term, args=None): params = {column: term for column in self._searched_columns} try: - response = requests.get(url, params=params, timeout=self._timeout, verify=self._verify_certificate) + response = requests.get( + url, params=params, timeout=self._timeout, verify=self._verify_certificate, + ) except RequestException as e: logger.error('Error connecting to %s: %s', url, e) return [] @@ -69,7 +71,9 @@ def first_match(self, term, args=None): params = {column: term for column in self._first_matched_columns} try: - response = requests.get(url, params=params, timeout=self._timeout, verify=self._verify_certificate) + response = requests.get( + url, params=params, timeout=self._timeout, verify=self._verify_certificate, + ) except RequestException as e: logger.error('Error connecting to %s: %s', url, e) return None @@ -90,7 +94,9 @@ def list(self, source_entry_ids, args=None): return [] try: - response = requests.get(self._list_url, timeout=self._timeout, verify=self._verify_certificate) + response = requests.get( + self._list_url, timeout=self._timeout, verify=self._verify_certificate, + ) except RequestException as e: logger.error('Error connecting to %s: %s', self._list_url, e) return [] diff --git a/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py b/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py index 4f2708a2..e560ea9f 100644 --- a/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py +++ b/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py @@ -1,4 +1,4 @@ -# Copyright 2015-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import unittest @@ -35,7 +35,9 @@ def test_that_search_queries_the_lookup_url(self, mocked_requests): source.search(term) - mocked_requests.get.assert_called_once_with(lookup_url, params=expected_params, timeout=s.timeout, verify=True) + mocked_requests.get.assert_called_once_with( + lookup_url, params=expected_params, timeout=s.timeout, verify=True, + ) @patch('wazo_dird.plugins.csv_ws_backend.plugin.requests') def test_that_first_match_queries_the_lookup_url(self, mocked_requests): @@ -56,7 +58,9 @@ def test_that_first_match_queries_the_lookup_url(self, mocked_requests): source.first_match(term) - mocked_requests.get.assert_called_once_with(lookup_url, params=expected_params, timeout=s.timeout, verify=True) + mocked_requests.get.assert_called_once_with( + lookup_url, params=expected_params, timeout=s.timeout, verify=True, + ) def test_that_list_returns_an_empty_list_if_no_unique_column(self): config = {'config': {'lookup_url': 'the_lookup_url', diff --git a/wazo_dird/plugins/default_json/tests/test_default_json_view.py b/wazo_dird/plugins/default_json/tests/test_default_json_view.py index b8b87ee0..30545490 100644 --- a/wazo_dird/plugins/default_json/tests/test_default_json_view.py +++ b/wazo_dird/plugins/default_json/tests/test_default_json_view.py @@ -85,8 +85,12 @@ def test_that_load_with_no_favorites_service_does_not_add_route(self): 'api': self.api, 'services': {}}) - assert_that(self.api.add_resource.call_args_list, not_(has_item(call(FavoritesRead, ANY)))) - assert_that(self.api.add_resource.call_args_list, not_(has_item(call(FavoritesWrite, ANY)))) + assert_that(self.api.add_resource.call_args_list, not_(has_item( + call(FavoritesRead, ANY), + ))) + assert_that(self.api.add_resource.call_args_list, not_(has_item( + call(FavoritesWrite, ANY), + ))) def test_that_load_adds_the_favorite_route(self): dependencies = { diff --git a/wazo_dird/plugins/favorites_service/plugin.py b/wazo_dird/plugins/favorites_service/plugin.py index 618ca5d4..9f8e9123 100644 --- a/wazo_dird/plugins/favorites_service/plugin.py +++ b/wazo_dird/plugins/favorites_service/plugin.py @@ -153,7 +153,10 @@ def new_favorite(self, tenant_uuid, source_name, contact_id, xivo_user_uuid): self._crud.create(xivo_user_uuid, backend, source_name, contact_id) event = FavoriteAddedEvent(self._xivo_uuid, xivo_user_uuid, source_name, contact_id) try: - self._bus.publish(event, headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True}) + self._bus.publish( + event, + headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True}, + ) except OSError as e: logger.error('failed to publish bus event %s', e) logger.info('%s', event) diff --git a/wazo_dird/plugins/ldap_backend/plugin.py b/wazo_dird/plugins/ldap_backend/plugin.py index b7425b3b..9af62597 100644 --- a/wazo_dird/plugins/ldap_backend/plugin.py +++ b/wazo_dird/plugins/ldap_backend/plugin.py @@ -34,7 +34,9 @@ def __init__(self, *args, **kwargs): def load(self, args): self._ldap_config = self.ldap_factory.new_ldap_config(args['config']) - self._ldap_result_formatter = self.ldap_factory.new_ldap_result_formatter(self._ldap_config) + self._ldap_result_formatter = self.ldap_factory.new_ldap_result_formatter( + self._ldap_config, + ) self._ldap_client = self.ldap_factory.new_ldap_client(self._ldap_config) self._ldap_client.set_up() @@ -101,7 +103,10 @@ class _LDAPConfig: DEFAULT_LDAP_TIMEOUT = 1.0 def __init__(self, config): - if not config.get('ldap_custom_filter') and not config.get(BaseSourcePlugin.SEARCHED_COLUMNS): + if ( + not config.get('ldap_custom_filter') + and not config.get(BaseSourcePlugin.SEARCHED_COLUMNS) + ): raise LookupError("%s need a searched_columns OR" "ldap_custom_filter in it's configuration" % config.get('name')) @@ -166,7 +171,9 @@ def build_search_filter(self, term): if ldap_custom_filter and searched_columns: custom_filter = self._build_search_filter_from_custom_filter(term_escaped) generated_filter = self._build_search_filter_from_searched_columns(term_escaped) - return self._build_filter_from_custom_and_generated_filter(custom_filter, generated_filter) + return self._build_filter_from_custom_and_generated_filter( + custom_filter, generated_filter, + ) elif ldap_custom_filter: return self._build_search_filter_from_custom_filter(term_escaped) elif searched_columns: @@ -180,8 +187,12 @@ def build_first_match_filter(self, term): if ldap_custom_filter and first_matched_columns: custom_filter = self._build_search_filter_from_custom_filter(term_escaped) - generated_filter = self._build_exact_search_filter_from_first_matched_columns(term_escaped) - return self._build_filter_from_custom_and_generated_filter(custom_filter, generated_filter) + generated_filter = self._build_exact_search_filter_from_first_matched_columns( + term_escaped, + ) + return self._build_filter_from_custom_and_generated_filter( + custom_filter, generated_filter, + ) elif ldap_custom_filter: return self._build_search_filter_from_custom_filter(term_escaped) elif first_matched_columns: @@ -195,12 +206,12 @@ def _build_search_filter_from_custom_filter(self, term_escaped): return self._config['ldap_custom_filter'].replace('%Q', term_escaped) def _build_search_filter_from_searched_columns(self, term_escaped): - l = list('(%s=*%s*)' % (attr, term_escaped) for attr in self.searched_columns()) - return self._build_filter_from_list(l) + list_ = list('(%s=*%s*)' % (attr, term_escaped) for attr in self.searched_columns()) + return self._build_filter_from_list(list_) def _build_exact_search_filter_from_first_matched_columns(self, term_escaped): - l = list('(%s=%s)' % (attr, term_escaped) for attr in self.first_matched_columns()) - return self._build_filter_from_list(l) + list_ = list('(%s=%s)' % (attr, term_escaped) for attr in self.first_matched_columns()) + return self._build_filter_from_list(list_) def _build_filter_from_list(self, l): if len(l) == 1: @@ -214,10 +225,10 @@ def build_list_filter(self, uids): unique_column = self._config[BaseSourcePlugin.UNIQUE_COLUMN] - l = [] + list_ = [] for uid in self._convert_uids(uids): - l.append('(%s=%s)' % (unique_column, uid)) - return self._build_filter_from_list(l) + list_.append('(%s=%s)' % (unique_column, uid)) + return self._build_filter_from_list(list_) def _convert_uids(self, uids): if self.has_binary_uuid(): @@ -226,7 +237,9 @@ def _convert_uids(self, uids): def _convert_binary_uid(self, uid): uid = uuid.UUID(uid).hex - return ''.join(character for byte in zip(itertools.repeat('\\'), uid[::2], uid[1::2]) for character in byte) + return ''.join( + c for byte in zip(itertools.repeat('\\'), uid[::2], uid[1::2]) for c in byte + ) class _LDAPClient: @@ -266,7 +279,10 @@ def _new_ldap_obj(self): def _bind(self): try: - self._ldap_obj.simple_bind_s(self._ldap_config.ldap_username(), self._ldap_config.ldap_password()) + self._ldap_obj.simple_bind_s( + self._ldap_config.ldap_username(), + self._ldap_config.ldap_password(), + ) except ldap.LDAPError as e: logger.error('LDAP "%s": bind error: %r', self._name, e) self._tear_down() @@ -305,7 +321,10 @@ def _search(self, filter_str, limit): except ldap.FILTER_ERROR: logger.warning('LDAP "%s": search error: invalid filter "%s"', self._name, filter_str) except ldap.NO_SUCH_OBJECT: - logger.warning('LDAP "%s": search error: no such object "%s"', self._name, self._ldap_config.ldap_base_dn()) + logger.warning( + 'LDAP "%s": search error: no such object "%s"', + self._name, self._ldap_config.ldap_base_dn(), + ) except ldap.TIMEOUT: logger.warning('LDAP "%s": search error: timed out', self._name) except ldap.LDAPError as e: diff --git a/wazo_dird/plugins/ldap_backend/schemas.py b/wazo_dird/plugins/ldap_backend/schemas.py index f0b08c1f..4636418c 100644 --- a/wazo_dird/plugins/ldap_backend/schemas.py +++ b/wazo_dird/plugins/ldap_backend/schemas.py @@ -20,7 +20,9 @@ class SourceSchema(BaseSourceSchema): ldap_network_timeout = fields.Float(validate=Range(min=0), default=0.3) ldap_timeout = fields.Float(validate=Range(min=0), default=1.0) unique_column = fields.String(Length(min=1, max=128), allownone=True, missing=None) - unique_column_format = fields.String(validate=OneOf(['string', 'binary_uuid']), missing='string') + unique_column_format = fields.String( + validate=OneOf(['string', 'binary_uuid']), missing='string', + ) class ListSchema(_ListSchema): diff --git a/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py b/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py index e9af0cf6..61b3e00b 100644 --- a/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py +++ b/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py @@ -1,4 +1,4 @@ -# Copyright 2015-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import ldap @@ -67,7 +67,10 @@ def test_search(self): def test_first_match(self): exten = '123456' self.ldap_config.build_first_match_filter.return_value = sentinel.filter - self.ldap_client.search.return_value = [(sentinel.result_1_dn, sentinel.result_1_attrs), sentinel.result_2] + self.ldap_client.search.return_value = [ + (sentinel.result_1_dn, sentinel.result_1_attrs), + sentinel.result_2, + ] self.ldap_result_formatter.format_one_result.return_value = sentinel.format_result self.ldap_plugin.load(self.config) @@ -75,7 +78,9 @@ def test_first_match(self): self.ldap_config.build_first_match_filter.assert_called_once_with(exten) self.ldap_client.search.assert_called_once_with(sentinel.filter, 1) - self.ldap_result_formatter.format_one_result.assert_called_once_with(sentinel.result_1_attrs) + self.ldap_result_formatter.format_one_result.assert_called_once_with( + sentinel.result_1_attrs, + ) self.assertIs(result, sentinel.format_result) def test_first_match_return_none_when_no_match(self): @@ -267,7 +272,9 @@ def test_ldap_network_timeout(self): def test_ldap_network_timeout_when_absent(self): ldap_config = self.new_ldap_config({}) - self.assertEqual(_LDAPConfig.DEFAULT_LDAP_NETWORK_TIMEOUT, ldap_config.ldap_network_timeout()) + self.assertEqual( + _LDAPConfig.DEFAULT_LDAP_NETWORK_TIMEOUT, ldap_config.ldap_network_timeout(), + ) def test_ldap_timeout(self): value = 42.0 @@ -353,7 +360,10 @@ def test_build_search_filter_with_searched_columns_and_custom_filter_unicode_ter 'ldap_custom_filter': str('(cn=*%Q*)'), }) - self.assertEqual('(&(cn=*Québec*)(sn=*Québec*))', ldap_config.build_search_filter('Québec')) + self.assertEqual( + '(&(cn=*Québec*)(sn=*Québec*))', + ldap_config.build_search_filter('Québec') + ) def test_build_search_filter_searched_columns_escape_term(self): ldap_config = _LDAPConfig({ @@ -521,7 +531,9 @@ def setUp(self): self.ldap_config.name.return_value = self.name self.ldap_config.unique_column.return_value = self.unique_column self.ldap_config.format_columns.return_value = self.format_columns - self.SourceResult = make_result_class('ldap', self.name, self.unique_column, self.format_columns) + self.SourceResult = make_result_class( + 'ldap', self.name, self.unique_column, self.format_columns, + ) def test_format(self): formatter = self._new_formatter(has_binary_uuid=False) diff --git a/wazo_dird/plugins/personal_service/plugin.py b/wazo_dird/plugins/personal_service/plugin.py index 69e62391..60f19c4a 100644 --- a/wazo_dird/plugins/personal_service/plugin.py +++ b/wazo_dird/plugins/personal_service/plugin.py @@ -57,7 +57,9 @@ def create_contact(self, contact_infos, token_infos): def create_contacts(self, contact_infos, token_infos): errors = [] to_add = [] - existing_contact_uuids = set([contact['id'] for contact in self._crud.list_personal_contacts()]) + existing_contact_uuids = set( + [contact['id'] for contact in self._crud.list_personal_contacts()], + ) for contact_info in contact_infos: try: @@ -80,7 +82,9 @@ def get_contact(self, contact_id, token_infos): def edit_contact(self, contact_id, contact_infos, token_infos): self.validate_contact(contact_infos) - return self._crud.edit_personal_contact(token_infos['xivo_user_uuid'], contact_id, contact_infos) + return self._crud.edit_personal_contact( + token_infos['xivo_user_uuid'], contact_id, contact_infos, + ) def remove_contact(self, contact_id, token_infos): self._crud.delete_personal_contact(token_infos['xivo_user_uuid'], contact_id) diff --git a/wazo_dird/plugins/phone/http.py b/wazo_dird/plugins/phone/http.py index 13cf5909..5b55483b 100644 --- a/wazo_dird/plugins/phone/http.py +++ b/wazo_dird/plugins/phone/http.py @@ -74,9 +74,15 @@ def __init__( self.auth_client = auth_client self.parser = reqparse.RequestParser() - self.parser.add_argument('limit', type=natural, required=False, default=max_item_per_page, location='args') - self.parser.add_argument('offset', type=natural, required=False, default=0, location='args') - self.parser.add_argument('term', type=str, required=True, help='term is missing', location='args') + self.parser.add_argument( + 'limit', type=natural, required=False, default=max_item_per_page, location='args', + ) + self.parser.add_argument( + 'offset', type=natural, required=False, default=0, location='args', + ) + self.parser.add_argument( + 'term', type=str, required=True, help='term is missing', location='args', + ) @required_acl('dird.directories.lookup.{profile}.{xivo_user_uuid}.read') def get(self, profile, xivo_user_uuid): @@ -134,6 +140,7 @@ def _get_user_tenant_uuid(self, user_uuid): raise NoSuchUser(user_uuid) raise + def _build_next_url(current): if current == 'menu': return request.base_url.replace('menu', 'input', 1) diff --git a/wazo_dird/plugins/phone/tests/test_phone_view.py b/wazo_dird/plugins/phone/tests/test_phone_view.py index c333a236..9b0e5d33 100644 --- a/wazo_dird/plugins/phone/tests/test_phone_view.py +++ b/wazo_dird/plugins/phone/tests/test_phone_view.py @@ -1,4 +1,4 @@ -# Copyright 2015-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later from unittest import TestCase @@ -20,7 +20,9 @@ def test_that_build_next_url_return_input_url_when_is_menu(self, MockedRequest): assert_that(result, equal_to(expected_result)) - def test_that_build_next_url_return_input_url_when_is_menu_with_profile_menu(self, MockedRequest): + def test_that_build_next_url_return_input_url_when_is_menu_with_profile_menu( + self, MockedRequest, + ): url = 'http://127.0.0.1:9489/0.1/directories/{}/menu/vendor' expected_result = url.format('input') MockedRequest.base_url = url.format('menu') @@ -36,7 +38,9 @@ def test_that_build_next_url_return_lookup_url_when_is_input(self, MockedRequest assert_that(result, equal_to(expected_result)) - def test_that_build_next_url_return_lookup_url_when_is_input_with_profile_input(self, MockedRequest): + def test_that_build_next_url_return_lookup_url_when_is_input_with_profile_input( + self, MockedRequest, + ): url = 'http://127.0.0.1:9489/0.1/directories/{}/input/vendor' expected_result = url.format('lookup') MockedRequest.base_url = url.format('input') diff --git a/wazo_dird/plugins/phone_helpers.py b/wazo_dird/plugins/phone_helpers.py index c4c43f11..983f19f5 100644 --- a/wazo_dird/plugins/phone_helpers.py +++ b/wazo_dird/plugins/phone_helpers.py @@ -11,7 +11,6 @@ def new_phone_lookup_service_from_args(dependencies): - # dependencies is the same "dependencies" argument that is passed to the load method of view plugins lookup_service = dependencies['services']['lookup'] display_service = dependencies['services']['display'] profile_service = dependencies['services']['profile'] @@ -44,8 +43,13 @@ def lookup(self, profile_config, term, tenant_uuid, user_uuid, token, limit=None formatted_results = formatter.format_results(lookup_results) formatted_results.sort(key=attrgetter('name', 'number')) + if limit is not None: + paginated_result = formatted_results[offset:offset + limit] + else: + paginated_result = formatted_results[offset:] + return { - 'results': formatted_results[offset:offset + limit] if limit is not None else formatted_results[offset:], + 'results': paginated_result, 'limit': limit, 'offset': offset, 'total': len(formatted_results), @@ -127,7 +131,9 @@ def _extract_results(self, fields): def _extract_number_from_pretty_number(self, pretty_number): number_with_parentheses = self._INVALID_CHARACTERS_REGEX.sub('', pretty_number) # Convert numbers +33(0)123456789 to 0033123456789 - number_with_parentheses = self._SPECIAL_NUMBER_REGEX.sub(r'00\1\2', number_with_parentheses) + number_with_parentheses = self._SPECIAL_NUMBER_REGEX.sub( + r'00\1\2', number_with_parentheses, + ) return self._PARENTHESES_REGEX.sub('', number_with_parentheses) @staticmethod diff --git a/wazo_dird/plugins/phonebook/http.py b/wazo_dird/plugins/phonebook/http.py index f80c7b3a..e2c4137c 100644 --- a/wazo_dird/plugins/phonebook/http.py +++ b/wazo_dird/plugins/phonebook/http.py @@ -10,7 +10,7 @@ from functools import wraps from xivo.tenant_flask_helpers import Tenant -from wazo_dird import auth +from wazo_dird.auth import required_acl from wazo_dird.exception import ( DatabaseServiceUnavailable, DuplicatedContactException, @@ -52,7 +52,9 @@ class _ArgParser: def __init__(self, args, valid_columns=None): self._search = args.get('search') - self._direction = self._get_string_from_valid_values(args, 'direction', ['asc', 'desc', None]) + self._direction = self._get_string_from_valid_values( + args, 'direction', ['asc', 'desc', None], + ) self._limit = self._get_positive_int(args, 'limit') self._offset = self._get_positive_int(args, 'offset') self._order = self._get_string_from_valid_values(args, 'order', valid_columns) @@ -126,7 +128,7 @@ class ContactAll(_Resource): NoSuchTenant: 404, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.create') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.create') @_default_error_route def post(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() @@ -137,7 +139,7 @@ def post(self, tenant, phonebook_id): request.json, ), 201 - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.read') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.read') @_default_error_route def get(self, tenant, phonebook_id): parser = _ArgParser(request.args) @@ -170,7 +172,7 @@ class PhonebookAll(_Resource): NoSuchTenant: 404, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.read') + @required_acl('dird.tenants.{tenant}.phonebooks.read') @_default_error_route def get(self, tenant): scoping_tenant = Tenant.autodetect() @@ -191,7 +193,7 @@ def get(self, tenant): 'total': count, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.create') + @required_acl('dird.tenants.{tenant}.phonebooks.create') @_default_error_route def post(self, tenant): scoping_tenant = Tenant.autodetect() @@ -209,7 +211,7 @@ class ContactImport(_Resource): NoSuchPhonebook: 404, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.create') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.create') @_default_error_route def post(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() @@ -250,7 +252,7 @@ class ContactOne(_Resource): NoSuchTenant: 404, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.read') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.read') @_default_error_route def get(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() @@ -261,7 +263,7 @@ def get(self, tenant, phonebook_id, contact_uuid): contact_uuid, ), 200 - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.delete') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.delete') @_default_error_route def delete(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() @@ -273,7 +275,7 @@ def delete(self, tenant, phonebook_id, contact_uuid): ) return '', 204 - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.update') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.update') @_default_error_route def put(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() @@ -296,7 +298,7 @@ class PhonebookOne(_Resource): NoSuchTenant: 404, } - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.delete') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.delete') @_default_error_route def delete(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() @@ -304,14 +306,14 @@ def delete(self, tenant, phonebook_id): self.phonebook_service.delete_phonebook(matching_tenant['uuid'], phonebook_id) return '', 204 - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.read') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.read') @_default_error_route def get(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) return self.phonebook_service.get_phonebook(matching_tenant['uuid'], phonebook_id), 200 - @auth.required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.update') + @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.update') @_default_error_route def put(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() diff --git a/wazo_dird/plugins/phonebook/plugin.py b/wazo_dird/plugins/phonebook/plugin.py index d279ba23..f4bac3a9 100644 --- a/wazo_dird/plugins/phonebook/plugin.py +++ b/wazo_dird/plugins/phonebook/plugin.py @@ -14,12 +14,6 @@ class PhonebookViewPlugin(BaseViewPlugin): - phonebook_all_url = '/tenants//phonebooks' - phonebook_one_url = '/tenants//phonebooks/' - contact_all_url = '/tenants//phonebooks//contacts' - contact_one_url = '/tenants//phonebooks//contacts/' - contact_import_url = '/tenants//phonebooks//contacts/import' - def load(self, dependencies=None): api = dependencies['api'] args = ( @@ -27,8 +21,28 @@ def load(self, dependencies=None): dependencies['auth_client'], ) - api.add_resource(ContactAll, self.contact_all_url, resource_class_args=args) - api.add_resource(ContactImport, self.contact_import_url, resource_class_args=args) - api.add_resource(ContactOne, self.contact_one_url, resource_class_args=args) - api.add_resource(PhonebookAll, self.phonebook_all_url, resource_class_args=args) - api.add_resource(PhonebookOne, self.phonebook_one_url, resource_class_args=args) + api.add_resource( + ContactAll, + '/tenants//phonebooks//contacts', + resource_class_args=args, + ) + api.add_resource( + ContactImport, + '/tenants//phonebooks//contacts/import', + resource_class_args=args, + ) + api.add_resource( + ContactOne, + '/tenants//phonebooks//contacts/', + resource_class_args=args, + ) + api.add_resource( + PhonebookAll, + '/tenants//phonebooks', + resource_class_args=args, + ) + api.add_resource( + PhonebookOne, + '/tenants//phonebooks/', + resource_class_args=args, + ) diff --git a/wazo_dird/plugins/phonebook_backend/schemas.py b/wazo_dird/plugins/phonebook_backend/schemas.py index e514f910..9daf88c6 100644 --- a/wazo_dird/plugins/phonebook_backend/schemas.py +++ b/wazo_dird/plugins/phonebook_backend/schemas.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: GPL-3.0-or-later from xivo.mallow import fields -from xivo.mallow.validate import Length from xivo.mallow_helpers import ListSchema as _ListSchema from wazo_dird.schemas import BaseSourceSchema diff --git a/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py b/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py index 33890f87..cca66724 100644 --- a/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py +++ b/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py @@ -92,7 +92,9 @@ def test_that_edit_with_no_name_raises(self): bodies = [{}, {'name': ''}, {'name': None}] for body in bodies: assert_that( - calling(self.service.edit_phonebook).with_args(s.tenant_uuid, s.phonebook_id, body), + calling(self.service.edit_phonebook).with_args( + s.tenant_uuid, s.phonebook_id, body, + ), raises(InvalidPhonebookException), body, ) @@ -153,7 +155,9 @@ def test_that_create_contact_raises_for_invalid_input(self): invalid_bodies = [{'': 'Foo'}, {}] for body in invalid_bodies: assert_that( - calling(self.service.create_contact).with_args(s.tenant_uuid, s.phonebook_id, body), + calling(self.service.create_contact).with_args( + s.tenant_uuid, s.phonebook_id, body, + ), raises(InvalidContactException), body, ) @@ -211,19 +215,27 @@ def test_get_contact(self): result = self.service.get_contact(s.tenant_uuid, s.phonebook_id, s.contact_uuid) assert_that(result, equal_to(self.contact_crud.get.return_value)) - self.contact_crud.get.assert_called_once_with(s.tenant_uuid, s.phonebook_id, s.contact_uuid) + self.contact_crud.get.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, s.contact_uuid, + ) class TestPhonebookServiceContactList(_BasePhonebookServiceTest): def setUp(self): super().setUp() - self._manolo = {'firstname': 'Manolo', 'lastname': 'Laporte-Carpentier', 'number': '5551111234'} + self._manolo = { + 'firstname': 'Manolo', + 'lastname': 'Laporte-Carpentier', + 'number': '5551111234', + } self._annabelle = {'firstname': 'Ännabelle', 'lastname': 'Courval', 'number': '5552221234'} self._gary_bob = {'firstname': 'Gary-Bob', 'lastname': 'Derome'} self._antonin = {'firstname': 'Antonin', 'lastname': 'Mongeau', 'number': '5554441234'} self._simon = {'firstname': 'Simon', 'lastname': "L'Espérance"} - self._contacts = [self._manolo, self._annabelle, self._gary_bob, self._antonin, self._simon] + self._contacts = [ + self._manolo, self._annabelle, self._gary_bob, self._antonin, self._simon, + ] def test_that_list_returns_the_db_result_when_no_pagination_or_sorting(self): self.contact_crud.list.return_value = self._contacts @@ -252,7 +264,9 @@ def test_that_list_can_be_limited(self): def test_that_list_can_have_an_offset(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, search=s.search, offset=3) + result = self.service.list_contact( + s.tenant_uuid, s.phonebook_id, search=s.search, offset=3, + ) self.contact_crud.list.assert_called_once_with( s.tenant_uuid, diff --git a/wazo_dird/plugins/profile_sources/plugin.py b/wazo_dird/plugins/profile_sources/plugin.py index e93d6336..231d2681 100644 --- a/wazo_dird/plugins/profile_sources/plugin.py +++ b/wazo_dird/plugins/profile_sources/plugin.py @@ -16,4 +16,8 @@ def load(self, dependencies): api = dependencies['api'] profile_service = dependencies['services']['profile'] args = (profile_service,) - api.add_resource(SourceResource, '/directories//sources', resource_class_args=args) + api.add_resource( + SourceResource, + '/directories//sources', + resource_class_args=args, + ) diff --git a/wazo_dird/plugins/profiles/http.py b/wazo_dird/plugins/profiles/http.py index 2f575ab5..fdc7e4a6 100644 --- a/wazo_dird/plugins/profiles/http.py +++ b/wazo_dird/plugins/profiles/http.py @@ -4,10 +4,7 @@ import logging from flask import request -from xivo.tenant_flask_helpers import ( - Tenant, - token, -) +from xivo.tenant_flask_helpers import Tenant from wazo_dird.auth import required_acl from wazo_dird.rest_api import AuthResource diff --git a/wazo_dird/plugins/reverse_service/plugin.py b/wazo_dird/plugins/reverse_service/plugin.py index 429a147f..384889ab 100644 --- a/wazo_dird/plugins/reverse_service/plugin.py +++ b/wazo_dird/plugins/reverse_service/plugin.py @@ -51,7 +51,9 @@ def reverse(self, profile_config, exten, profile, args=None, xivo_user_uuid=None args = args or {} futures = [] sources = self.source_from_profile(profile_config) - logger.debug('Reverse lookup for {} in sources {}'.format(exten, [source.name for source in sources])) + logger.debug( + 'Reverse lookup for %s in sources %s', exten, [source.name for source in sources], + ) for source in sources: args['token'] = token args['xivo_user_uuid'] = xivo_user_uuid diff --git a/wazo_dird/plugins/sample_backend/plugin.py b/wazo_dird/plugins/sample_backend/plugin.py index d7d1e3cb..08c691d1 100644 --- a/wazo_dird/plugins/sample_backend/plugin.py +++ b/wazo_dird/plugins/sample_backend/plugin.py @@ -1,19 +1,21 @@ -# Copyright 2014-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2014-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later from wazo_dird import BaseSourcePlugin from wazo_dird import make_result_class -class SamplePlugin(BaseSourcePlugin): +DESC = 'It works but this wazo-dird installation is still using the default configuration' +SAMPLE_RESULT = { + 'id': 1, + 'firstname': 'John', + 'lastname': 'Doe', + 'number': '555', + 'description': DESC, +} + - _sample_result = { - 'id': 1, - 'firstname': 'John', - 'lastname': 'Doe', - 'number': '555', - 'description': 'It works but this wazo-dird installation is still using the default configuration', - } +class SamplePlugin(BaseSourcePlugin): def load(self, args): self._config = args.get('config', {}) @@ -22,7 +24,7 @@ def load(self, args): backend = self._config.get('backend', '') SourceResult = make_result_class(backend, self._name, 'id', self._format_columns) - self._result = SourceResult(self._sample_result) + self._result = SourceResult(SAMPLE_RESULT) def search(self, term, args=None): return [self._result] diff --git a/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py b/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py index b4113914..73afbf77 100644 --- a/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py +++ b/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py @@ -1,4 +1,4 @@ -# Copyright 2014-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2014-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import unittest @@ -10,6 +10,8 @@ from ..plugin import SamplePlugin +MSG = 'It works but this wazo-dird installation is still using the default configuration' + class TestSampleBackend(unittest.TestCase): @@ -26,7 +28,7 @@ def test_search(self): 'firstname': 'John', 'lastname': 'Doe', 'number': '555', - 'description': 'It works but this wazo-dird installation is still using the default configuration', + 'description': MSG, }) self.source.load({}) @@ -41,7 +43,7 @@ def test_first_match(self): 'firstname': 'John', 'lastname': 'Doe', 'number': '555', - 'description': 'It works but this wazo-dird installation is still using the default configuration', + 'description': MSG, }) self.source.load({}) diff --git a/wazo_dird/plugins/source_result.py b/wazo_dird/plugins/source_result.py index 62fa4023..3dd94c86 100644 --- a/wazo_dird/plugins/source_result.py +++ b/wazo_dird/plugins/source_result.py @@ -13,7 +13,10 @@ def format(self, format_string, *args, **kwargs): try: return super().format(format_string, *args, **kwargs).strip() except Exception as e: - logger.debug('skipping string formatting %s %s: %s', format_string, e.__class__.__name__, e) + logger.debug( + 'skipping string formatting %s %s: %s', + format_string, e.__class__.__name__, e, + ) return None def get_value(self, key, args, kwargs): @@ -33,7 +36,10 @@ class _SourceResult: source = None _format_columns = {} - def __init__(self, fields, xivo_id=None, agent_id=None, user_id=None, user_uuid=None, endpoint_id=None): + def __init__( + self, fields, xivo_id=None, agent_id=None, + user_id=None, user_uuid=None, endpoint_id=None, + ): self._formatter = _NoErrorFormatter() self.fields = dict(fields) source_entry_id = self.get_unique() if self._unique_column else None @@ -50,9 +56,10 @@ def get_unique(self): try: return str(self.fields[self._unique_column]) except KeyError: - - msg = '{source} is not properly configured, the unique column is not part of the result'.format(source=self.source) - logger.exception(msg) + logger.exception( + '%s is not properly configured, the unique column is not part of the result', + self.source, + ) return None def source_entry_id(self): @@ -81,7 +88,10 @@ def __repr__(self): self.relations['endpoint_id']) -def make_result_class(source_backend, source_name, unique_column=None, format_columns=None, is_deletable=False, is_personal=False): +def make_result_class( + source_backend, source_name, + unique_column=None, format_columns=None, is_deletable=False, is_personal=False, +): if not unique_column: unique_column = _SourceResult._unique_column if not format_columns: diff --git a/wazo_dird/rest_api.py b/wazo_dird/rest_api.py index 1d8e0616..18b97054 100644 --- a/wazo_dird/rest_api.py +++ b/wazo_dird/rest_api.py @@ -73,7 +73,10 @@ def run(self): wsgi_app=wsgi_app) server.ssl_adapter = http_helpers.ssl_adapter(https_config['certificate'], https_config['private_key']) - logger.debug('WSGIServer starting... uid: %s, listen: %s:%s', os.getuid(), bind_addr[0], bind_addr[1]) + logger.debug( + 'WSGIServer starting... uid: %s, listen: %s:%s', + os.getuid(), bind_addr[0], bind_addr[1], + ) for route in http_helpers.list_routes(self.app): logger.debug(route) @@ -104,7 +107,9 @@ class LegacyErrorCatchingResource(Resource): class LegacyAuthResource(LegacyErrorCatchingResource): - method_decorators = [auth_verifier.verify_token] + LegacyErrorCatchingResource.method_decorators + method_decorators = [ + auth_verifier.verify_token, + ] + LegacyErrorCatchingResource.method_decorators class ErrorCatchingResource(Resource): diff --git a/wazo_dird/service_discovery.py b/wazo_dird/service_discovery.py index 07918c2d..05d599d5 100644 --- a/wazo_dird/service_discovery.py +++ b/wazo_dird/service_discovery.py @@ -1,4 +1,4 @@ -# Copyright 2016-2018 The Wazo Authors (see the AUTHORS file) +# Copyright 2016-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import requests @@ -8,6 +8,7 @@ def self_check(port): url = 'https://localhost:{}/0.1/directories/lookup/foobar/headers'.format(port) try: - return requests.get(url, headers={'accept': 'application/json'}, verify=False).status_code == 401 + response = requests.get(url, headers={'accept': 'application/json'}, verify=False) + return response.status_code == 401 except Exception: return False diff --git a/wazo_dird/source_manager.py b/wazo_dird/source_manager.py index 5cbc15e3..f2490df2 100644 --- a/wazo_dird/source_manager.py +++ b/wazo_dird/source_manager.py @@ -4,13 +4,10 @@ import logging import threading -from collections import defaultdict import stevedore -from stevedore import ( - EnabledExtensionManager, - NamedExtensionManager, -) +from stevedore import NamedExtensionManager + from xivo import plugin_helpers from wazo_dird import exception diff --git a/wazo_dird/tests/test_config.py b/wazo_dird/tests/test_config.py index f2e82e27..5e1c03de 100644 --- a/wazo_dird/tests/test_config.py +++ b/wazo_dird/tests/test_config.py @@ -14,7 +14,7 @@ @patch('wazo_dird.config.open', create=True) class TestConfig(TestCase): - def test_load_when_no_args_and_no_default_config_file_then_return_default_values(self, mock_open): + def test_load_when_no_args_and_no_default_config_file_then_default_values(self, mock_open): mock_open.side_effect = IOError('no such file') config._DEFAULT_CONFIG = { 'config': 'default', diff --git a/wazo_dird/tests/test_controller.py b/wazo_dird/tests/test_controller.py index ca39da04..95972713 100644 --- a/wazo_dird/tests/test_controller.py +++ b/wazo_dird/tests/test_controller.py @@ -28,7 +28,9 @@ def tearDown(self): def test_run_starts_rest_api(self): config = self._create_config(**{ - 'rest_api': {'https': {'listen': '127.0.0.1', 'port': '9489', 'certificate': 'my-certificate'}}, + 'rest_api': { + 'https': {'listen': '127.0.0.1', 'port': '9489', 'certificate': 'my-certificate'}, + }, 'debug': s.debug, 'service_discovery': {'enabled': False}, }) diff --git a/wazo_dird/tests/test_main.py b/wazo_dird/tests/test_main.py index e6c1be21..08b53ab4 100644 --- a/wazo_dird/tests/test_main.py +++ b/wazo_dird/tests/test_main.py @@ -55,7 +55,9 @@ def test_main_setup_logging(self, load_config, _, xivo_logging, *__): s.log_level, ) - def test_main_when_config_user_then_change_user(self, load_config, _, __, change_user, *___): + def test_main_when_config_user_then_change_user( + self, load_config, _, __, change_user, *___ + ): load_config.return_value = { 'debug': s.debug, 'log_filename': s.log_filename, @@ -69,7 +71,9 @@ def test_main_when_config_user_then_change_user(self, load_config, _, __, change change_user.assert_called_once_with(s.user) - def test_main_when_no_config_user_then_dont_change_user(self, load_config, _, __, change_user, *___): + def test_main_when_no_config_user_then_dont_change_user( + self, load_config, _, __, change_user, *___ + ): load_config.return_value = { 'debug': s.debug, 'log_filename': s.log_filename, From 8dd665bd83624917fd51b046ca211cee7b172cee Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Mon, 8 Jul 2019 14:36:43 -0400 Subject: [PATCH 08/24] tox: add the flake8 config --- tox.ini | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tox.ini b/tox.ini index 735bf27f..36c62bf4 100644 --- a/tox.ini +++ b/tox.ini @@ -47,3 +47,11 @@ commands = -black --skip-string-normalization --check . flake8 +[flake8] +exclude = + .tox + .eggs + integration_tests/assets/scripts +show-source = true +max-line-length = 99 +application-import-names = wazo_dird From 2908956d14c0f5c07a456e9b69c320f7fca95701 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Mon, 8 Jul 2019 16:08:27 -0400 Subject: [PATCH 09/24] zuul: add unittests --- zuul.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/zuul.yaml b/zuul.yaml index faa20531..a9f17349 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -1,3 +1,4 @@ - project: templates: - wazo-tox-linters + - wazo-tox-py35 From e4606c2eee5f13e270bfa48725fbb4d701a7d13e Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Mon, 8 Jul 2019 16:29:46 -0400 Subject: [PATCH 10/24] zuul: add a bindep.txt --- bindep.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 bindep.txt diff --git a/bindep.txt b/bindep.txt new file mode 100644 index 00000000..82846871 --- /dev/null +++ b/bindep.txt @@ -0,0 +1 @@ +libldap2-dev [platform:dpkg] From 8034f516b8a8c43919f39e1e8a84245ca83a0a45 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 9 Jul 2019 10:18:40 -0400 Subject: [PATCH 11/24] tox: add integration tests --- .../test-requirements-for-tox.txt | 29 +++++++++++++++++++ test-requirements.txt | 7 +++-- tox.ini | 12 ++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) create mode 100644 integration_tests/test-requirements-for-tox.txt diff --git a/integration_tests/test-requirements-for-tox.txt b/integration_tests/test-requirements-for-tox.txt new file mode 100644 index 00000000..1d63ed9d --- /dev/null +++ b/integration_tests/test-requirements-for-tox.txt @@ -0,0 +1,29 @@ +https://github.com/wazo-pbx/xivo-bus/archive/master.zip +https://github.com/wazo-pbx/xivo-test-helpers/archive/master.zip +https://github.com/wazo-pbx/xivo-lib-python/archive/master.zip + +babel +flask-babel +docker-compose +openapi-spec-validator +pyhamcrest +# pytest 4.2.0 has a bug: https://github.com/pytest-dev/pytest/issues/4700 +pytest!=4.2.0 +python-ldap +sh +mock + +# for database tests +psycopg2-binary +sqlalchemy==1.0.15 +unidecode==0.04.19 +cheroot==6.5.2 +kombu +stevedore +flask-restful==0.3.5 +flask-cors==3.0.2 +marshmallow==2.16.3 +https://github.com/wazo-pbx/wazo-auth-client/archive/master.zip +https://github.com/wazo-pbx/wazo-confd-client/archive/master.zip +https://github.com/wazo-pbx/xivo-lib-rest-client/archive/master.zip +https://github.com/wazo-pbx/wazo-dird-client/archive/master.zip diff --git a/test-requirements.txt b/test-requirements.txt index b9f16c7c..a9e9adab 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,3 +1,4 @@ -mock -pytest -pyhamcrest +# Backward compatiblity for jenkins + +-r test-requirements-for-tox.txt +-e .. diff --git a/tox.ini b/tox.ini index 36c62bf4..c97571ce 100644 --- a/tox.ini +++ b/tox.ini @@ -47,6 +47,18 @@ commands = -black --skip-string-normalization --check . flake8 +[testenv:integration] +usedevelop = true +deps = -rintegration_tests/test-requirements-for-tox.txt +changedir = integration_tests +passenv = + WAZO_TEST_DOCKER_OVERRIDE_EXTRA +commands = + make test-setup + pytest {posargs} +whitelist_externals: + make + [flake8] exclude = .tox From 56015a170b78d32081bc1e92264253f1df37f59f Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 9 Jul 2019 10:19:23 -0400 Subject: [PATCH 12/24] zuul: add integration tests --- zuul.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/zuul.yaml b/zuul.yaml index a9f17349..1bb29906 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -2,3 +2,4 @@ templates: - wazo-tox-linters - wazo-tox-py35 + - wazo-tox-integration From 13f9748912503b5a06829f3db4ca60b4acf7bac3 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 9 Jul 2019 10:24:00 -0400 Subject: [PATCH 13/24] zuul: remove the bindep.txt our zuul configuration does not allow packages to be installed --- bindep.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 bindep.txt diff --git a/bindep.txt b/bindep.txt deleted file mode 100644 index 82846871..00000000 --- a/bindep.txt +++ /dev/null @@ -1 +0,0 @@ -libldap2-dev [platform:dpkg] From b0c6cccd6282463b8eb36c07ea690e5343ed5152 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 9 Jul 2019 16:28:03 -0400 Subject: [PATCH 14/24] tox: testenv set python3 --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index c97571ce..94d20ab8 100644 --- a/tox.ini +++ b/tox.ini @@ -8,6 +8,7 @@ envlist = py35, pycodestyle, pylint skipsdist = true [testenv] +basepython = python3 commands = pytest --junitxml=unit-tests.xml --cov=wazo_dird --cov-report term --cov-report xml:coverage.xml wazo_dird deps = From 182143bb5eb1c327c6e9f7cd4fb6e47609c8f137 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Tue, 9 Jul 2019 16:29:45 -0400 Subject: [PATCH 15/24] tests: restore the test-requirements.txt at the root --- test-requirements.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test-requirements.txt b/test-requirements.txt index a9e9adab..2fef9dbf 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,4 +1,4 @@ -# Backward compatiblity for jenkins +mock +pytest +pyhamcrest --r test-requirements-for-tox.txt --e .. From ede9e7260e8a52343bf0e4ca2b4876c17956e476 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Wed, 10 Jul 2019 11:16:32 -0400 Subject: [PATCH 16/24] tox: add black --- tox.ini | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tox.ini b/tox.ini index 94d20ab8..241fe552 100644 --- a/tox.ini +++ b/tox.ini @@ -16,6 +16,13 @@ deps = -rtest-requirements.txt pytest-cov +[testenv:black] +skip_install = true +deps = black +commands = black --skip-string-normalization . +exclude = + integration_tests/assets/scripts + [testenv:pycodestyle] basepython = python3 # E501: line too long (80 chars) @@ -68,3 +75,6 @@ exclude = show-source = true max-line-length = 99 application-import-names = wazo_dird +# W503: line break before binary operator +# E203: whitespace before ':' warnings +ignore = E203, W503 From 4de32b24f163d6d1773cbe819707603fb5724f01 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Wed, 10 Jul 2019 11:17:19 -0400 Subject: [PATCH 17/24] styling: run black --- alembic/env.py | 13 +- ...7_remove_the_db_uri_from_the_phonebook_.py | 14 +- ...d4_add_the_profile_configuration_tables.py | 20 +- ...dd_the_hash_column_on_the_contact_table.py | 4 +- ...88fa7_remove_duplicate_contact_field_id.py | 35 +- ...352_allow_contacts_to_be_in_a_phonebook.py | 12 +- .../25e9a6782cac_add_source_fields.py | 10 +- .../265d68f9c337_add_contact_relation.py | 2 +- ...ed2_add_tables_for_the_phonebook_plugin.py | 8 +- ...ca548ddf_add_a_uuid_to_the_tenant_table.py | 33 +- .../5bfdd2178269_add_the_display_tables.py | 31 +- ...14e21_fix_foreign_key_on_profile_source.py | 53 +- .../9a38ab587987_add_a_source_uuid.py | 33 +- .../b0df0bc0ce37_add_the_contact_table.py | 7 +- ...a744_fix_foreign_key_on_profile_display.py | 15 +- .../d237d33088c6_add_the_user_table.py | 3 +- ...55_remove_the_db_uri_from_the_personal_.py | 14 +- .../assets/microsoft-mock/main.py | 10 +- ...sset.csv_ws_utf8_with_pipes_with_ssl.ws.py | 5 +- .../docker/broken-plugins/setup.py | 9 +- .../broken_backend.py | 2 - .../suite/base_dird_integration_test.py | 5 +- integration_tests/suite/helpers/base.py | 234 ++++-- integration_tests/suite/helpers/config.py | 160 ++-- integration_tests/suite/helpers/constants.py | 6 +- .../suite/helpers/fixtures/db.py | 10 +- .../suite/helpers/fixtures/http.py | 24 +- .../suite/test_authentication.py | 34 +- integration_tests/suite/test_auto_create.py | 156 ++-- integration_tests/suite/test_backends.py | 19 +- .../suite/test_conference_backend.py | 124 ++-- .../suite/test_conference_contacts.py | 45 +- .../suite/test_conference_http.py | 168 ++--- integration_tests/suite/test_config_view.py | 9 +- .../suite/test_core_functionality.py | 249 ++++--- integration_tests/suite/test_csv_backend.py | 52 +- integration_tests/suite/test_csv_http.py | 134 ++-- .../suite/test_csv_ws_backend.py | 63 +- integration_tests/suite/test_csv_ws_http.py | 142 ++-- integration_tests/suite/test_database.py | 685 +++++++++--------- .../suite/test_database_reconnect.py | 5 +- .../suite/test_dird_phonebook_backend.py | 21 +- integration_tests/suite/test_displays.py | 159 ++-- integration_tests/suite/test_favorites.py | 146 ++-- integration_tests/suite/test_https.py | 15 +- integration_tests/suite/test_ldap_backend.py | 62 +- integration_tests/suite/test_ldap_http.py | 142 ++-- .../suite/test_office365_backend.py | 215 +++--- integration_tests/suite/test_personal.py | 215 +++--- .../suite/test_personal_export.py | 32 +- integration_tests/suite/test_personal_http.py | 162 ++--- .../suite/test_personal_import.py | 116 ++- integration_tests/suite/test_phone.py | 20 +- integration_tests/suite/test_phone_view.py | 67 +- integration_tests/suite/test_phonebook.py | 94 +-- .../suite/test_phonebook_http.py | 160 ++-- integration_tests/suite/test_profiles.py | 434 ++++++----- .../suite/test_service_discovery_service.py | 40 +- integration_tests/suite/test_sources.py | 180 +++-- .../suite/test_tenant_migration.py | 77 +- .../suite/test_wazo_user_backend.py | 205 +++--- .../suite/test_wazo_user_contacts.py | 97 +-- .../suite/test_wazo_user_http.py | 147 ++-- setup.py | 25 +- wazo_dird/bus.py | 11 +- wazo_dird/config.py | 71 +- wazo_dird/controller.py | 1 - wazo_dird/database/__init__.py | 13 +- wazo_dird/database/models.py | 77 +- wazo_dird/database/queries/base.py | 10 +- wazo_dird/database/queries/display.py | 29 +- wazo_dird/database/queries/favorite.py | 45 +- wazo_dird/database/queries/personal.py | 104 +-- wazo_dird/database/queries/phonebook.py | 105 +-- wazo_dird/database/queries/profile.py | 54 +- wazo_dird/database/queries/source.py | 40 +- wazo_dird/database/queries/tenant.py | 3 +- wazo_dird/database/schemas.py | 5 +- wazo_dird/exception.py | 30 +- wazo_dird/helpers.py | 27 +- wazo_dird/main.py | 14 +- .../plugin_helpers/confd_client_registry.py | 5 +- wazo_dird/plugin_manager.py | 10 +- wazo_dird/plugins/api/http.py | 18 +- wazo_dird/plugins/api/plugin.py | 1 - wazo_dird/plugins/backends/http.py | 7 +- wazo_dird/plugins/backends/plugin.py | 5 +- wazo_dird/plugins/backends/service.py | 8 +- wazo_dird/plugins/base_plugins.py | 1 - wazo_dird/plugins/cleanup_service/plugin.py | 7 +- wazo_dird/plugins/conference_backend/http.py | 10 +- .../plugins/conference_backend/plugin.py | 14 +- .../conference_backend/tests/test_schemas.py | 58 +- wazo_dird/plugins/config/plugin.py | 3 +- wazo_dird/plugins/config_service/plugin.py | 25 +- .../tests/test_config_service.py | 11 +- wazo_dird/plugins/csv_backend/http.py | 13 +- wazo_dird/plugins/csv_backend/plugin.py | 12 +- .../csv_backend/tests/test_csv_plugin.py | 90 +-- wazo_dird/plugins/csv_ws_backend/http.py | 13 +- wazo_dird/plugins/csv_ws_backend/plugin.py | 41 +- wazo_dird/plugins/csv_ws_backend/schemas.py | 10 +- .../csv_ws_backend/tests/test_csv_ws.py | 77 +- wazo_dird/plugins/default_json/http.py | 80 +- wazo_dird/plugins/default_json/plugin.py | 21 +- .../tests/test_default_json_view.py | 295 +++++--- .../plugins/default_json/tests/test_http.py | 13 +- wazo_dird/plugins/display_service/plugin.py | 7 +- wazo_dird/plugins/displays/http.py | 19 +- wazo_dird/plugins/displays/plugin.py | 5 +- wazo_dird/plugins/favorites_service/plugin.py | 30 +- .../tests/test_favorites_service.py | 67 +- wazo_dird/plugins/headers/http.py | 1 - wazo_dird/plugins/headers/plugin.py | 1 - .../plugins/headers/tests/test_header_view.py | 1 - wazo_dird/plugins/ldap_backend/http.py | 13 +- wazo_dird/plugins/ldap_backend/plugin.py | 79 +- wazo_dird/plugins/ldap_backend/schemas.py | 8 +- .../ldap_backend/tests/test_ldap_plugin.py | 217 +++--- wazo_dird/plugins/lookup_service/plugin.py | 11 +- .../lookup_service/tests/test_lookup.py | 5 +- .../plugins/office365_backend/exceptions.py | 4 +- wazo_dird/plugins/office365_backend/http.py | 13 +- wazo_dird/plugins/office365_backend/plugin.py | 20 +- .../plugins/office365_backend/schemas.py | 2 +- .../plugins/office365_backend/services.py | 28 +- .../tests/test_office365_plugin.py | 26 +- wazo_dird/plugins/personal/http.py | 62 +- wazo_dird/plugins/personal/plugin.py | 6 +- .../personal/tests/test_personal_view.py | 26 +- wazo_dird/plugins/personal_backend/http.py | 13 +- wazo_dird/plugins/personal_backend/plugin.py | 19 +- .../tests/test_personal_backend.py | 50 +- wazo_dird/plugins/personal_service/plugin.py | 24 +- wazo_dird/plugins/phone/http.py | 74 +- .../plugins/phone/tests/test_phone_view.py | 5 +- wazo_dird/plugins/phone_helpers.py | 17 +- wazo_dird/plugins/phonebook/http.py | 124 ++-- wazo_dird/plugins/phonebook/plugin.py | 14 +- wazo_dird/plugins/phonebook_backend/http.py | 13 +- wazo_dird/plugins/phonebook_backend/plugin.py | 12 +- .../tests/test_dird_phonebook_backend.py | 20 +- wazo_dird/plugins/phonebook_service/plugin.py | 30 +- .../tests/test_phonebook_service.py | 257 +++---- .../plugins/phonebook_tenant_modifier/http.py | 1 - .../phonebook_tenant_modifier/plugin.py | 6 +- .../phonebook_tenant_modifier/service.py | 5 +- wazo_dird/plugins/polycom/plugin.py | 3 +- wazo_dird/plugins/profile_service/plugin.py | 18 +- wazo_dird/plugins/profile_sources/http.py | 11 +- wazo_dird/plugins/profile_sources/plugin.py | 5 +- .../tests/test_source_plugin.py | 7 +- wazo_dird/plugins/profiles/http.py | 19 +- wazo_dird/plugins/profiles/plugin.py | 5 +- wazo_dird/plugins/profiles/schemas.py | 1 - wazo_dird/plugins/reverse_service/plugin.py | 19 +- wazo_dird/plugins/sample_backend/plugin.py | 9 +- .../tests/test_sample_backend.py | 37 +- .../service_discovery_service/plugin.py | 35 +- .../tests/test_service_discovery_service.py | 115 ++- wazo_dird/plugins/source_result.py | 60 +- wazo_dird/plugins/source_service/plugin.py | 7 +- wazo_dird/plugins/sources/http.py | 12 +- wazo_dird/plugins/sources/plugin.py | 5 +- wazo_dird/plugins/status/http.py | 1 - wazo_dird/plugins/status/plugin.py | 4 +- .../plugins/tests/base_http_view_test_case.py | 1 - wazo_dird/plugins/tests/test_source_result.py | 123 ++-- .../plugins/wazo_user_backend/contact.py | 1 - wazo_dird/plugins/wazo_user_backend/http.py | 6 +- wazo_dird/plugins/wazo_user_backend/plugin.py | 40 +- .../tests/test_contact_list.py | 14 +- .../wazo_user_backend/tests/test_schemas.py | 40 +- .../tests/test_wazo_user_backend.py | 118 ++- wazo_dird/rest_api.py | 32 +- wazo_dird/schemas.py | 29 +- wazo_dird/service_discovery.py | 4 +- wazo_dird/source_manager.py | 5 +- wazo_dird/tests/test_config.py | 5 +- wazo_dird/tests/test_controller.py | 59 +- wazo_dird/tests/test_helpers.py | 1 - wazo_dird/tests/test_main.py | 17 +- wazo_dird/tests/test_plugin_manager.py | 26 +- wazo_dird/tests/test_source_manager.py | 1 - 184 files changed, 4637 insertions(+), 4568 deletions(-) diff --git a/alembic/env.py b/alembic/env.py index 0062227d..68b94732 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -32,8 +32,7 @@ def run_migrations_offline(): """ url = config.get_main_option("sqlalchemy.url") - context.configure(url=url, - version_table='alembic_version_dird') + context.configure(url=url, version_table='alembic_version_dird') with context.begin_transaction(): context.run_migrations() @@ -47,13 +46,13 @@ def run_migrations_online(): """ engine = engine_from_config( - config.get_section(config.config_ini_section), - prefix='sqlalchemy.', - poolclass=pool.NullPool) + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) connection = engine.connect() - context.configure(connection=connection, - version_table='alembic_version_dird') + context.configure(connection=connection, version_table='alembic_version_dird') try: with context.begin_transaction(): diff --git a/alembic/versions/07e71f4c5437_remove_the_db_uri_from_the_phonebook_.py b/alembic/versions/07e71f4c5437_remove_the_db_uri_from_the_phonebook_.py index c3dbb08b..3b4041e1 100644 --- a/alembic/versions/07e71f4c5437_remove_the_db_uri_from_the_phonebook_.py +++ b/alembic/versions/07e71f4c5437_remove_the_db_uri_from_the_phonebook_.py @@ -13,26 +13,24 @@ down_revision = 'efe763372855' source_table = sa.sql.table( - 'dird_source', - sa.sql.column('extra_fields'), - sa.sql.column('backend'), + 'dird_source', sa.sql.column('extra_fields'), sa.sql.column('backend') ) def upgrade(): op.execute( - source_table - .update() + source_table.update() .where(source_table.c.backend == 'phonebook') .values(extra_fields=None) ) def downgrade(): - extra_fields = '''{"db_uri": "postgresql://asterisk:proformatique@localhost/asterisk"}''' + extra_fields = ( + '''{"db_uri": "postgresql://asterisk:proformatique@localhost/asterisk"}''' + ) op.execute( - source_table - .update() + source_table.update() .where(source_table.c.backend == 'phonebook') .values(extra_fields=extra_fields) ) diff --git a/alembic/versions/0f0470be22d4_add_the_profile_configuration_tables.py b/alembic/versions/0f0470be22d4_add_the_profile_configuration_tables.py index a34938c4..ae284e95 100644 --- a/alembic/versions/0f0470be22d4_add_the_profile_configuration_tables.py +++ b/alembic/versions/0f0470be22d4_add_the_profile_configuration_tables.py @@ -23,12 +23,7 @@ def upgrade(): server_default=sa.text('uuid_generate_v4()'), primary_key=True, ), - sa.Column( - 'name', - sa.Text(), - nullable=False, - unique=True, - ) + sa.Column('name', sa.Text(), nullable=False, unique=True), ) op.create_table( @@ -45,16 +40,12 @@ def upgrade(): sa.ForeignKey('dird_tenant.uuid', ondelete='CASCADE'), nullable=False, ), - sa.Column( - 'name', - sa.Text(), - nullable=False, - ), + sa.Column('name', sa.Text(), nullable=False), sa.Column( 'display_uuid', sa.String(36), sa.ForeignKey('dird_display.uuid', ondelete='SET NULL'), - ) + ), ) op.create_table( @@ -77,10 +68,7 @@ def upgrade(): sa.ForeignKey('dird_service.uuid', ondelete='CASCADE'), nullable=False, ), - sa.Column( - 'config', - JSON, - ), + sa.Column('config', JSON), ) op.create_table( diff --git a/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py b/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py index 6a41e57a..36681650 100644 --- a/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py +++ b/alembic/versions/1c6344eac1bd_add_the_hash_column_on_the_contact_table.py @@ -18,9 +18,7 @@ def upgrade(): - op.add_column(table_name, sa.Column(column_name, - sa.String(40), - nullable=False)) + op.add_column(table_name, sa.Column(column_name, sa.String(40), nullable=False)) op.create_unique_constraint(constraint_name, table_name, [column_name, 'user_uuid']) diff --git a/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py b/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py index 974a395f..769b3638 100644 --- a/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py +++ b/alembic/versions/1e0397088fa7_remove_duplicate_contact_field_id.py @@ -12,11 +12,13 @@ revision = '1e0397088fa7' down_revision = '1e66a71e0352' -contact_field_table = sql.table('dird_contact_fields', - sql.column('id'), - sql.column('name'), - sql.column('value'), - sql.column('contact_uuid')) +contact_field_table = sql.table( + 'dird_contact_fields', + sql.column('id'), + sql.column('name'), + sql.column('value'), + sql.column('contact_uuid'), +) def upgrade(): @@ -33,19 +35,24 @@ def upgrade(): def purge_divergent_id_contact_fields(): - query = contact_field_table.delete().where(sql.and_( - contact_field_table.c.name == 'id', - contact_field_table.c.value != contact_field_table.c.contact_uuid, - )) + query = contact_field_table.delete().where( + sql.and_( + contact_field_table.c.name == 'id', + contact_field_table.c.value != contact_field_table.c.contact_uuid, + ) + ) op.get_bind().execute(query) def get_id_contact_field_rows(): - id_contact_fields = (sql.select([contact_field_table.c.id, contact_field_table.c.contact_uuid]) - .where(sql.and_( - contact_field_table.c.name == 'id', - contact_field_table.c.value == contact_field_table.c.contact_uuid, - ))) + id_contact_fields = sql.select( + [contact_field_table.c.id, contact_field_table.c.contact_uuid] + ).where( + sql.and_( + contact_field_table.c.name == 'id', + contact_field_table.c.value == contact_field_table.c.contact_uuid, + ) + ) return op.get_bind().execute(id_contact_fields) diff --git a/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py b/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py index 7e840c6b..44aee93d 100644 --- a/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py +++ b/alembic/versions/1e66a71e0352_allow_contacts_to_be_in_a_phonebook.py @@ -18,10 +18,14 @@ def upgrade(): op.alter_column(table_name, 'user_uuid', nullable=True) - op.add_column(table_name, - sa.Column('phonebook_id', - sa.Integer(), - sa.ForeignKey('dird_phonebook.id', ondelete='CASCADE'))) + op.add_column( + table_name, + sa.Column( + 'phonebook_id', + sa.Integer(), + sa.ForeignKey('dird_phonebook.id', ondelete='CASCADE'), + ), + ) op.create_unique_constraint(constraint_name, table_name, ['hash', 'phonebook_id']) diff --git a/alembic/versions/25e9a6782cac_add_source_fields.py b/alembic/versions/25e9a6782cac_add_source_fields.py index 5286bfb2..d617ba76 100644 --- a/alembic/versions/25e9a6782cac_add_source_fields.py +++ b/alembic/versions/25e9a6782cac_add_source_fields.py @@ -7,11 +7,7 @@ from alembic import op import sqlalchemy as sa -from sqlalchemy.dialects.postgresql import ( - ARRAY, - HSTORE, - JSON, -) +from sqlalchemy.dialects.postgresql import ARRAY, HSTORE, JSON # revision identifiers, used by Alembic. revision = '25e9a6782cac' @@ -29,7 +25,9 @@ def upgrade(): op.add_column(table_name, sa.Column('first_matched_columns', ARRAY(sa.Text))) op.add_column(table_name, sa.Column('format_columns', HSTORE)) op.add_column(table_name, sa.Column('extra_fields', JSON)) - op.create_unique_constraint('dird_source_tenant_name', table_name, ['tenant_uuid', 'name']) + op.create_unique_constraint( + 'dird_source_tenant_name', table_name, ['tenant_uuid', 'name'] + ) op.drop_constraint('dird_source_name_key', table_name) diff --git a/alembic/versions/265d68f9c337_add_contact_relation.py b/alembic/versions/265d68f9c337_add_contact_relation.py index 99e531d8..5a7a5135 100644 --- a/alembic/versions/265d68f9c337_add_contact_relation.py +++ b/alembic/versions/265d68f9c337_add_contact_relation.py @@ -24,7 +24,7 @@ def upgrade(): sa.String(38), sa.ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), nullable=False, - ) + ), ) diff --git a/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py b/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py index 14ef75c9..26ce790e 100644 --- a/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py +++ b/alembic/versions/28e9ff92ed2_add_tables_for_the_phonebook_plugin.py @@ -26,7 +26,13 @@ def upgrade(): op.create_table( 'dird_tenant', Column('id', Integer(), primary_key=True), - Column('name', String(255), CheckConstraint("name != ''"), unique=True, nullable=False), + Column( + 'name', + String(255), + CheckConstraint("name != ''"), + unique=True, + nullable=False, + ), ) op.create_table( 'dird_phonebook', diff --git a/alembic/versions/401aca548ddf_add_a_uuid_to_the_tenant_table.py b/alembic/versions/401aca548ddf_add_a_uuid_to_the_tenant_table.py index 0e7ad288..aee11516 100644 --- a/alembic/versions/401aca548ddf_add_a_uuid_to_the_tenant_table.py +++ b/alembic/versions/401aca548ddf_add_a_uuid_to_the_tenant_table.py @@ -28,46 +28,35 @@ def upgrade(): sa.String(UUID_LENGTH), nullable=False, server_default=sa.text('uuid_generate_v4()'), - ) + ), ) op.add_column( - phonebook_table_name, - sa.Column( - 'tenant_uuid', - sa.String(UUID_LENGTH), - ) + phonebook_table_name, sa.Column('tenant_uuid', sa.String(UUID_LENGTH)) ) tenant_table = sa.sql.table( - tenant_table_name, - sa.sql.column('id'), - sa.sql.column('uuid'), + tenant_table_name, sa.sql.column('id'), sa.sql.column('uuid') ) id_uuid_query = sa.sql.select([tenant_table.c.id, tenant_table.c.uuid]) id_uuid_rows = op.get_bind().execute(id_uuid_query).fetchall() phonebook_table = sa.sql.table( - phonebook_table_name, - sa.sql.column('tenant_id'), - sa.sql.column('tenant_uuid'), + phonebook_table_name, sa.sql.column('tenant_id'), sa.sql.column('tenant_uuid') ) for id_, uuid in id_uuid_rows: op.execute( - phonebook_table - .update() + phonebook_table.update() .where(phonebook_table.c.tenant_id == id_) .values(tenant_uuid=uuid) ) op.alter_column(phonebook_table_name, 'tenant_uuid', nullable=False) - op.execute('ALTER TABLE dird_phonebook DROP CONSTRAINT dird_phonebook_tenant_id_fkey CASCADE') - op.execute('ALTER TABLE dird_tenant DROP CONSTRAINT dird_tenant_pkey CASCADE') - op.create_primary_key( - 'dird_tenant_pkey', - tenant_table_name, - ['uuid'], + op.execute( + 'ALTER TABLE dird_phonebook DROP CONSTRAINT dird_phonebook_tenant_id_fkey CASCADE' ) + op.execute('ALTER TABLE dird_tenant DROP CONSTRAINT dird_tenant_pkey CASCADE') + op.create_primary_key('dird_tenant_pkey', tenant_table_name, ['uuid']) op.create_foreign_key( 'dird_phonebook_tenant_uuid_fkey', phonebook_table_name, @@ -77,9 +66,7 @@ def upgrade(): ondelete='CASCADE', ) op.create_unique_constraint( - 'dird_phonebook_name_tenant_uuid', - phonebook_table_name, - ['name', 'tenant_uuid'], + 'dird_phonebook_name_tenant_uuid', phonebook_table_name, ['name', 'tenant_uuid'] ) op.drop_column(tenant_table_name, 'id') op.drop_column(phonebook_table_name, 'tenant_id') diff --git a/alembic/versions/5bfdd2178269_add_the_display_tables.py b/alembic/versions/5bfdd2178269_add_the_display_tables.py index 04e92d46..e907c22f 100644 --- a/alembic/versions/5bfdd2178269_add_the_display_tables.py +++ b/alembic/versions/5bfdd2178269_add_the_display_tables.py @@ -28,11 +28,7 @@ def upgrade(): sa.ForeignKey('dird_tenant.uuid', ondelete='CASCADE'), nullable=False, ), - sa.Column( - 'name', - sa.Text(), - nullable=False, - ) + sa.Column('name', sa.Text(), nullable=False), ) op.create_table( @@ -49,26 +45,11 @@ def upgrade(): sa.ForeignKey('dird_display.uuid', ondelete='CASCADE'), nullable=False, ), - sa.Column( - 'field', - sa.Text(), - ), - sa.Column( - 'default', - sa.Text(), - ), - sa.Column( - 'type', - sa.Text(), - ), - sa.Column( - 'title', - sa.Text(), - ), - sa.Column( - 'number_display', - sa.Text(), - ), + sa.Column('field', sa.Text()), + sa.Column('default', sa.Text()), + sa.Column('type', sa.Text()), + sa.Column('title', sa.Text()), + sa.Column('number_display', sa.Text()), ) diff --git a/alembic/versions/86b01bf14e21_fix_foreign_key_on_profile_source.py b/alembic/versions/86b01bf14e21_fix_foreign_key_on_profile_source.py index a8fffacd..2ef11698 100644 --- a/alembic/versions/86b01bf14e21_fix_foreign_key_on_profile_source.py +++ b/alembic/versions/86b01bf14e21_fix_foreign_key_on_profile_source.py @@ -19,22 +19,17 @@ def upgrade(): # dird_profile_service_source.profile_tenant_uuid # dird_profile_service_source.source_tenant_uuid op.add_column( - 'dird_profile_service', - sa.Column('profile_tenant_uuid', sa.String(36)), + 'dird_profile_service', sa.Column('profile_tenant_uuid', sa.String(36)) ) op.add_column( - 'dird_profile_service_source', - sa.Column('profile_tenant_uuid', sa.String(36)), + 'dird_profile_service_source', sa.Column('profile_tenant_uuid', sa.String(36)) ) op.add_column( - 'dird_profile_service_source', - sa.Column('source_tenant_uuid', sa.String(36)), + 'dird_profile_service_source', sa.Column('source_tenant_uuid', sa.String(36)) ) profile_table = sa.sql.table( - 'dird_profile', - sa.sql.column('uuid'), - sa.sql.column('tenant_uuid') + 'dird_profile', sa.sql.column('uuid'), sa.sql.column('tenant_uuid') ) profile_service_table = sa.sql.table( 'dird_profile_service', @@ -50,18 +45,17 @@ def upgrade(): sa.sql.column('source_tenant_uuid'), ) source_table = sa.sql.table( - 'dird_source', - sa.sql.column('uuid'), - sa.sql.column('tenant_uuid') + 'dird_source', sa.sql.column('uuid'), sa.sql.column('tenant_uuid') ) - profile_to_tenant_query = sa.sql.select([profile_table.c.uuid, profile_table.c.tenant_uuid]) + profile_to_tenant_query = sa.sql.select( + [profile_table.c.uuid, profile_table.c.tenant_uuid] + ) rows = op.get_bind().execute(profile_to_tenant_query).fetchall() profile_to_tenant = {row.uuid: row.tenant_uuid for row in rows} for uuid, tenant_uuid in profile_to_tenant.items(): op.execute( - profile_service_table - .update() + profile_service_table.update() .where(profile_service_table.c.profile_uuid == uuid) .values(profile_tenant_uuid=tenant_uuid) ) @@ -73,28 +67,26 @@ def upgrade(): profile_service_to_tenant = {row.uuid: row.profile_tenant_uuid for row in rows} for uuid, tenant_uuid in profile_service_to_tenant.items(): op.execute( - profile_service_source_table - .update() + profile_service_source_table.update() .where(profile_service_source_table.c.profile_service_uuid == uuid) .values(profile_tenant_uuid=tenant_uuid) ) - source_to_tenant_query = sa.sql.select([source_table.c.uuid, source_table.c.tenant_uuid]) + source_to_tenant_query = sa.sql.select( + [source_table.c.uuid, source_table.c.tenant_uuid] + ) rows = op.get_bind().execute(source_to_tenant_query).fetchall() source_to_tenant = {row.uuid: row.tenant_uuid for row in rows} for uuid, tenant_uuid in source_to_tenant.items(): op.execute( - profile_service_source_table - .update() + profile_service_source_table.update() .where(profile_service_source_table.c.source_uuid == uuid) .values(source_tenant_uuid=tenant_uuid) ) # Make the tenant/uuid pair unique op.create_unique_constraint( - 'dird_profile_uuid_tenant', - 'dird_profile', - ['uuid', 'tenant_uuid'], + 'dird_profile_uuid_tenant', 'dird_profile', ['uuid', 'tenant_uuid'] ) op.create_unique_constraint( 'dird_profile_service_uuid_tenant', @@ -102,9 +94,7 @@ def upgrade(): ['uuid', 'profile_tenant_uuid'], ) op.create_unique_constraint( - 'dird_source_uuid_tenant', - 'dird_source', - ['uuid', 'tenant_uuid'], + 'dird_source_uuid_tenant', 'dird_source', ['uuid', 'tenant_uuid'] ) # Create new foreign keys using the foreign tenant_uuid keys @@ -134,17 +124,13 @@ def upgrade(): ) # Drop the old foreign keys - op.drop_constraint( - 'dird_profile_service_profile_uuid_fkey', - 'dird_profile_service', - ) + op.drop_constraint('dird_profile_service_profile_uuid_fkey', 'dird_profile_service') op.drop_constraint( 'dird_profile_service_source_profile_service_uuid_fkey', 'dird_profile_service_source', ) op.drop_constraint( - 'dird_profile_service_source_source_uuid_fkey', - 'dird_profile_service_source', + 'dird_profile_service_source_source_uuid_fkey', 'dird_profile_service_source' ) @@ -177,8 +163,7 @@ def downgrade(): # Remove the new FK op.drop_constraint( - 'dird_profile_service_profile_uuid_tenant_fkey', - 'dird_profile_service', + 'dird_profile_service_profile_uuid_tenant_fkey', 'dird_profile_service' ) op.drop_constraint( 'dird_profile_service_source_profile_service_uuid_tenant_fkey', diff --git a/alembic/versions/9a38ab587987_add_a_source_uuid.py b/alembic/versions/9a38ab587987_add_a_source_uuid.py index 68bf8b24..2c27ed8f 100644 --- a/alembic/versions/9a38ab587987_add_a_source_uuid.py +++ b/alembic/versions/9a38ab587987_add_a_source_uuid.py @@ -30,46 +30,31 @@ def upgrade(): sa.String(UUID_LENGTH), nullable=False, server_default=sa.text('uuid_generate_v4()'), - ) - ) - op.add_column( - favorite_table_name, - sa.Column( - 'source_uuid', - sa.String(UUID_LENGTH), - ) + ), ) + op.add_column(favorite_table_name, sa.Column('source_uuid', sa.String(UUID_LENGTH))) - source_table = sql.table( - source_table_name, - sql.column('id'), - sql.column('uuid'), - ) + source_table = sql.table(source_table_name, sql.column('id'), sql.column('uuid')) id_uuid_query = sql.select([source_table.c.id, source_table.c.uuid]) id_uuid_rows = op.get_bind().execute(id_uuid_query).fetchall() favorite_table = sql.table( - favorite_table_name, - sql.column('source_id'), - sql.column('source_uuid'), + favorite_table_name, sql.column('source_id'), sql.column('source_uuid') ) for id_, uuid in id_uuid_rows: op.execute( - favorite_table - .update() + favorite_table.update() .where(favorite_table.c.source_id == id_) .values(source_uuid=uuid) ) op.alter_column(favorite_table_name, 'source_uuid', nullable=False) op.execute('ALTER TABLE dird_favorite DROP CONSTRAINT dird_favorite_pkey CASCADE') - op.execute('ALTER TABLE dird_favorite DROP CONSTRAINT dird_favorite_source_id_fkey CASCADE') - op.execute('ALTER TABLE dird_source DROP CONSTRAINT dird_source_pkey CASCADE') - op.create_primary_key( - 'dird_source_pkey', - source_table_name, - ['uuid'], + op.execute( + 'ALTER TABLE dird_favorite DROP CONSTRAINT dird_favorite_source_id_fkey CASCADE' ) + op.execute('ALTER TABLE dird_source DROP CONSTRAINT dird_source_pkey CASCADE') + op.create_primary_key('dird_source_pkey', source_table_name, ['uuid']) op.create_primary_key( 'dird_favorite_pkey', favorite_table_name, diff --git a/alembic/versions/b0df0bc0ce37_add_the_contact_table.py b/alembic/versions/b0df0bc0ce37_add_the_contact_table.py index 47112eca..5db56eb4 100644 --- a/alembic/versions/b0df0bc0ce37_add_the_contact_table.py +++ b/alembic/versions/b0df0bc0ce37_add_the_contact_table.py @@ -19,7 +19,12 @@ def upgrade(): op.create_table( table_name, - Column('uuid', String(38), server_default=text('uuid_generate_v4()'), primary_key=True), + Column( + 'uuid', + String(38), + server_default=text('uuid_generate_v4()'), + primary_key=True, + ), ) diff --git a/alembic/versions/b22ffe8fa744_fix_foreign_key_on_profile_display.py b/alembic/versions/b22ffe8fa744_fix_foreign_key_on_profile_display.py index 6f3a97c8..7256e043 100644 --- a/alembic/versions/b22ffe8fa744_fix_foreign_key_on_profile_display.py +++ b/alembic/versions/b22ffe8fa744_fix_foreign_key_on_profile_display.py @@ -14,23 +14,18 @@ def upgrade(): - op.add_column( - 'dird_profile', - sa.Column('display_tenant_uuid', sa.String(36)), - ) + op.add_column('dird_profile', sa.Column('display_tenant_uuid', sa.String(36))) profile_table = sa.sql.table( 'dird_profile', sa.sql.column('tenant_uuid'), sa.sql.column('display_tenant_uuid'), ) - op.execute(profile_table.update().values( - display_tenant_uuid=profile_table.c.tenant_uuid - )) + op.execute( + profile_table.update().values(display_tenant_uuid=profile_table.c.tenant_uuid) + ) op.create_unique_constraint( - 'dird_display_uuid_tenant', - 'dird_display', - ['uuid', 'tenant_uuid'], + 'dird_display_uuid_tenant', 'dird_display', ['uuid', 'tenant_uuid'] ) op.create_foreign_key( 'dird_profile_display_uuid_tenant_fkey', diff --git a/alembic/versions/d237d33088c6_add_the_user_table.py b/alembic/versions/d237d33088c6_add_the_user_table.py index 27136ee2..d18edf10 100644 --- a/alembic/versions/d237d33088c6_add_the_user_table.py +++ b/alembic/versions/d237d33088c6_add_the_user_table.py @@ -17,8 +17,7 @@ def upgrade(): - op.create_table(table_name, - Column('xivo_user_uuid', String(38), primary_key=True)) + op.create_table(table_name, Column('xivo_user_uuid', String(38), primary_key=True)) def downgrade(): diff --git a/alembic/versions/efe763372855_remove_the_db_uri_from_the_personal_.py b/alembic/versions/efe763372855_remove_the_db_uri_from_the_personal_.py index 8c5b634a..c5e1b118 100644 --- a/alembic/versions/efe763372855_remove_the_db_uri_from_the_personal_.py +++ b/alembic/versions/efe763372855_remove_the_db_uri_from_the_personal_.py @@ -13,26 +13,24 @@ down_revision = '86b01bf14e21' source_table = sa.sql.table( - 'dird_source', - sa.sql.column('extra_fields'), - sa.sql.column('backend'), + 'dird_source', sa.sql.column('extra_fields'), sa.sql.column('backend') ) def upgrade(): op.execute( - source_table - .update() + source_table.update() .where(source_table.c.backend == 'personal') .values(extra_fields=None) ) def downgrade(): - extra_fields = '''{"db_uri": "postgresql://asterisk:proformatique@localhost/asterisk"}''' + extra_fields = ( + '''{"db_uri": "postgresql://asterisk:proformatique@localhost/asterisk"}''' + ) op.execute( - source_table - .update() + source_table.update() .where(source_table.c.backend == 'personal') .values(extra_fields=extra_fields) ) diff --git a/integration_tests/assets/microsoft-mock/main.py b/integration_tests/assets/microsoft-mock/main.py index f58e984e..b9bf9761 100644 --- a/integration_tests/assets/microsoft-mock/main.py +++ b/integration_tests/assets/microsoft-mock/main.py @@ -12,7 +12,6 @@ class MicrosoftMock(Resource): - def get(self): term = request.args.get('search') print('Looking for term: {}.'.format(term), file=sys.stderr) @@ -27,12 +26,10 @@ def get(self): "mobilePhone": "", "businessPhones": ['5555555555'], "emailAddresses": [ - { - "address": "wbros@wazoquebec.onmicrosoft.com" - }, + {"address": "wbros@wazoquebec.onmicrosoft.com"}, + {}, {}, - {} - ] + ], } ] } @@ -41,7 +38,6 @@ def get(self): class MicrosoftErrorMock(Resource): - def get(self): print('Microsoft is sending an error response.', file=sys.stderr) return '', 404 diff --git a/integration_tests/assets/scripts/asset.csv_ws_utf8_with_pipes_with_ssl.ws.py b/integration_tests/assets/scripts/asset.csv_ws_utf8_with_pipes_with_ssl.ws.py index 5533d3f1..cf1b0985 100755 --- a/integration_tests/assets/scripts/asset.csv_ws_utf8_with_pipes_with_ssl.ws.py +++ b/integration_tests/assets/scripts/asset.csv_ws_utf8_with_pipes_with_ssl.ws.py @@ -11,7 +11,10 @@ app = Flask(__name__) -context = ('/usr/local/share/ssl/dird/server.crt', '/usr/local/share/ssl/dird/server.key') +context = ( + '/usr/local/share/ssl/dird/server.crt', + '/usr/local/share/ssl/dird/server.key', +) headers = ['id', 'firstname', 'lastname', 'number'] entries = [ diff --git a/integration_tests/docker/broken-plugins/setup.py b/integration_tests/docker/broken-plugins/setup.py index c73ab097..a605b13f 100644 --- a/integration_tests/docker/broken-plugins/setup.py +++ b/integration_tests/docker/broken-plugins/setup.py @@ -6,20 +6,15 @@ setup( name='wazo-dird-broken-plugins', version='1.0', - description='Wazo Directory Daemon broken plugins', - author='The Wazo Authors', author_email='dev+pkg@wazo.community', - url='https://github.com/wazo-pbx/wazo-dird', - packages=find_packages(), - entry_points={ 'wazo_dird.backends': [ 'broken = xivo_dird_broken_plugins.broken_backend:BrokenPlugin', 'broken_lookup = xivo_dird_broken_plugins.broken_backend:BrokenLookup', - ], - } + ] + }, ) diff --git a/integration_tests/docker/broken-plugins/xivo_dird_broken_plugins/broken_backend.py b/integration_tests/docker/broken-plugins/xivo_dird_broken_plugins/broken_backend.py index 49d00de6..e5a5d0d7 100644 --- a/integration_tests/docker/broken-plugins/xivo_dird_broken_plugins/broken_backend.py +++ b/integration_tests/docker/broken-plugins/xivo_dird_broken_plugins/broken_backend.py @@ -3,13 +3,11 @@ class BrokenPlugin: - def __init__(self): raise RuntimeError('BROKEN') class BrokenLookup: - def load(self, config): return diff --git a/integration_tests/suite/base_dird_integration_test.py b/integration_tests/suite/base_dird_integration_test.py index 8e46bd71..45160e25 100644 --- a/integration_tests/suite/base_dird_integration_test.py +++ b/integration_tests/suite/base_dird_integration_test.py @@ -21,12 +21,9 @@ def absolute_file_name(asset_name, path): class BackendWrapper: - def __init__(self, backend, dependencies): manager = DriverManager( - namespace='wazo_dird.backends', - name=backend, - invoke_on_load=True, + namespace='wazo_dird.backends', name=backend, invoke_on_load=True ) self._source = manager.driver self._source.load(dependencies) diff --git a/integration_tests/suite/helpers/base.py b/integration_tests/suite/helpers/base.py index 12ead23f..8bc4b4d6 100644 --- a/integration_tests/suite/helpers/base.py +++ b/integration_tests/suite/helpers/base.py @@ -8,11 +8,7 @@ from sqlalchemy.engine import create_engine from sqlalchemy.orm import scoped_session, sessionmaker -from hamcrest import ( - assert_that, - equal_to, - has_entries, -) +from hamcrest import assert_that, equal_to, has_entries from xivo import url_helpers from xivo_test_helpers import until @@ -48,7 +44,6 @@ class DirdAssetRunningTestCase(AssetLaunchingTestCase): class DBRunningTestCase(DirdAssetRunningTestCase): - @classmethod def setUpClass(cls): super().setUpClass() @@ -88,7 +83,9 @@ class AutoConfiguredDirdTestCase(DBRunningTestCase): @classmethod def setUpClass(cls): super().setUpClass() - cls.mock_auth_client = MockAuthClient('localhost', cls.service_port(9497, 'auth')) + cls.mock_auth_client = MockAuthClient( + 'localhost', cls.service_port(9497, 'auth') + ) cls.config = cls.config_factory(cls.Session) cls.config.setup() @@ -99,7 +96,6 @@ def tearDownClass(cls): class BaseDirdIntegrationTest(AutoConfiguredDirdTestCase): - @classmethod def setUpClass(cls): super().setUpClass() @@ -109,9 +105,7 @@ def setUpClass(cls): auth_port = cls.service_port(9497, 'auth') auth_client = AuthClient('localhost', auth_port, verify_certificate=False) auth_client.users.new( - uuid=VALID_UUID, - tenant_uuid=MAIN_TENANT, - username='foobar', + uuid=VALID_UUID, tenant_uuid=MAIN_TENANT, username='foobar' ) except Exception: pass @@ -213,28 +207,41 @@ def post_phonebook(cls, tenant, phonebook_body, token=VALID_TOKEN_MAIN_TENANT): return cls.post(url, json=phonebook_body, token=token) @classmethod - def put_phonebook(cls, tenant, phonebook_id, phonebook_body, token=VALID_TOKEN_MAIN_TENANT): + def put_phonebook( + cls, tenant, phonebook_id, phonebook_body, token=VALID_TOKEN_MAIN_TENANT + ): url = cls.url('tenants', tenant, 'phonebooks', phonebook_id) return cls.put(url, json=phonebook_body, token=token) @classmethod def post_phonebook_contact( - cls, tenant, phonebook_id, contact_body, token=VALID_TOKEN_MAIN_TENANT + cls, tenant, phonebook_id, contact_body, token=VALID_TOKEN_MAIN_TENANT ): url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts') return cls.post(url, json=contact_body, token=token) @classmethod - def import_phonebook_contact(cls, tenant, phonebook_id, body, token=VALID_TOKEN_MAIN_TENANT): - url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts', 'import') + def import_phonebook_contact( + cls, tenant, phonebook_id, body, token=VALID_TOKEN_MAIN_TENANT + ): + url = cls.url( + 'tenants', tenant, 'phonebooks', phonebook_id, 'contacts', 'import' + ) headers = {'X-Auth-Token': token, 'Context-Type': 'text/csv; charset=utf-8'} return cls.post(url, data=body, headers=headers) @classmethod def put_phonebook_contact( - cls, tenant, phonebook_id, contact_uuid, contact_body, token=VALID_TOKEN_MAIN_TENANT, + cls, + tenant, + phonebook_id, + contact_uuid, + contact_body, + token=VALID_TOKEN_MAIN_TENANT, ): - url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_uuid) + url = cls.url( + 'tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_uuid + ) return cls.put(url, json=contact_body, token=token) @classmethod @@ -268,7 +275,9 @@ def import_personal_result(cls, csv, token=None, encoding='utf-8'): return cls.post(url, data=csv, headers=headers) @classmethod - def import_personal(cls, personal_infos, token=VALID_TOKEN_MAIN_TENANT, encoding='utf-8'): + def import_personal( + cls, personal_infos, token=VALID_TOKEN_MAIN_TENANT, encoding='utf-8' + ): response = cls.import_personal_result(personal_infos, token, encoding) assert_that(response.status_code, equal_to(201)) return response.json() @@ -319,14 +328,16 @@ def get_phonebook(cls, tenant, phonebook_id, token=VALID_TOKEN_MAIN_TENANT): @classmethod def get_phonebook_contact( - cls, tenant, phonebook_id, contact_uuid, token=VALID_TOKEN_MAIN_TENANT, + cls, tenant, phonebook_id, contact_uuid, token=VALID_TOKEN_MAIN_TENANT ): - url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_uuid) + url = cls.url( + 'tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_uuid + ) return cls.get(url, token=token) @classmethod def list_phonebook_contacts( - cls, tenant, phonebook_id, token=VALID_TOKEN_MAIN_TENANT, **kwargs + cls, tenant, phonebook_id, token=VALID_TOKEN_MAIN_TENANT, **kwargs ): url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts') return cls.get(url, params=kwargs, token=token) @@ -359,9 +370,11 @@ def delete_phonebook(cls, tenant, phonebook_id, token=VALID_TOKEN_MAIN_TENANT): @classmethod def delete_phonebook_contact( - cls, tenant, phonebook_id, contact_id, token=VALID_TOKEN_MAIN_TENANT, + cls, tenant, phonebook_id, contact_id, token=VALID_TOKEN_MAIN_TENANT ): - url = cls.url('tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_id) + url = cls.url( + 'tenants', tenant, 'phonebooks', phonebook_id, 'contacts', contact_id + ) return cls.delete(url, token=token) @classmethod @@ -391,7 +404,9 @@ def get_menu_cisco_result(cls, profile, xivo_user_uuid, proxy=None, token=None): return cls.get(url, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) @classmethod - def get_menu_cisco(cls, profile, xivo_user_uuid, proxy=None, token=VALID_TOKEN_MAIN_TENANT): + def get_menu_cisco( + cls, profile, xivo_user_uuid, proxy=None, token=VALID_TOKEN_MAIN_TENANT + ): response = cls.get_menu_cisco_result(profile, xivo_user_uuid, proxy, token) assert_that(response.status_code, equal_to(200)) return response.text @@ -402,25 +417,43 @@ def get_input_cisco_result(cls, profile, xivo_user_uuid, proxy=None, token=None) return cls.get(url, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) @classmethod - def get_input_cisco(cls, profile, xivo_user_uuid, proxy=None, token=VALID_TOKEN_MAIN_TENANT): + def get_input_cisco( + cls, profile, xivo_user_uuid, proxy=None, token=VALID_TOKEN_MAIN_TENANT + ): response = cls.get_input_cisco_result(profile, xivo_user_uuid, proxy, token) assert_that(response.status_code, equal_to(200)) return response.text @classmethod - def get_lookup_cisco_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_cisco_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'cisco') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod def get_lookup_cisco( - cls, profile, xivo_user_uuid, term, - proxy=None, token=VALID_TOKEN_MAIN_TENANT, limit=None, offset=None, + cls, + profile, + xivo_user_uuid, + term, + proxy=None, + token=VALID_TOKEN_MAIN_TENANT, + limit=None, + offset=None, ): response = cls.get_lookup_cisco_result( - profile, xivo_user_uuid, proxy, term, token, limit, offset, + profile, xivo_user_uuid, proxy, term, token, limit, offset ) assert_that(response.status_code, equal_to(200)) return response.text @@ -431,11 +464,21 @@ def get_input_aastra_result(cls, profile, xivo_user_uuid, proxy=None, token=None return cls.get(url, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) @classmethod - def get_lookup_aastra_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_aastra_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'aastra') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod def get_input_polycom_result(cls, profile, xivo_user_uuid, proxy=None, token=None): @@ -443,11 +486,21 @@ def get_input_polycom_result(cls, profile, xivo_user_uuid, proxy=None, token=Non return cls.get(url, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) @classmethod - def get_lookup_polycom_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_polycom_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'polycom') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod def get_input_snom_result(cls, profile, xivo_user_uuid, proxy=None, token=None): @@ -455,39 +508,89 @@ def get_input_snom_result(cls, profile, xivo_user_uuid, proxy=None, token=None): return cls.get(url, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) @classmethod - def get_lookup_snom_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_snom_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'snom') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod - def get_lookup_thomson_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_thomson_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'thomson') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod - def get_lookup_yealink_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_yealink_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'yealink') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod - def get_lookup_gigaset_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_gigaset_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'gigaset') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @classmethod - def get_lookup_htek_result(cls, profile, xivo_user_uuid, - proxy=None, term=None, token=None, limit=None, offset=None): + def get_lookup_htek_result( + cls, + profile, + xivo_user_uuid, + proxy=None, + term=None, + token=None, + limit=None, + offset=None, + ): url = cls.url('directories', 'lookup', profile, xivo_user_uuid, 'htek') params = {'term': term, 'limit': limit, 'offset': offset} - return cls.get(url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy}) + return cls.get( + url, params=params, headers={'X-Auth-Token': token, 'Proxy-URL': proxy} + ) @staticmethod def delete(*args, **kwargs): @@ -506,24 +609,24 @@ def get(*args, **kwargs): @staticmethod def post(*args, **kwargs): token = kwargs.pop('token', None) - kwargs.setdefault('headers', {'X-Auth-Token': token, 'Content-Type': 'application/json'}) + kwargs.setdefault( + 'headers', {'X-Auth-Token': token, 'Content-Type': 'application/json'} + ) kwargs.setdefault('verify', CA_CERT) return requests.post(*args, **kwargs) @staticmethod def put(*args, **kwargs): token = kwargs.pop('token', None) - kwargs.setdefault('headers', {'X-Auth-Token': token, 'Content-Type': 'application/json'}) + kwargs.setdefault( + 'headers', {'X-Auth-Token': token, 'Content-Type': 'application/json'} + ) kwargs.setdefault('verify', CA_CERT) return requests.put(*args, **kwargs) @staticmethod def assert_list_result(result, items, total, filtered): - assert_that(result, has_entries( - items=items, - total=total, - filtered=filtered, - )) + assert_that(result, has_entries(items=items, total=total, filtered=filtered)) class BasePhonebookTestCase(BaseDirdIntegrationTest): @@ -549,11 +652,14 @@ def tearDown(self): def set_tenants(self, *tenant_names): items = [{'uuid': DIRD_TOKEN_TENANT}] for tenant_name in tenant_names: - self.tenants.setdefault(tenant_name, { - 'uuid': str(uuid.uuid4()), - 'name': tenant_name, - 'parent_uuid': DIRD_TOKEN_TENANT, - }) + self.tenants.setdefault( + tenant_name, + { + 'uuid': str(uuid.uuid4()), + 'name': tenant_name, + 'parent_uuid': DIRD_TOKEN_TENANT, + }, + ) items.append(self.tenants[tenant_name]) self.mock_auth_client.set_tenants(*items) diff --git a/integration_tests/suite/helpers/config.py b/integration_tests/suite/helpers/config.py index 1d3545c4..6308caf7 100644 --- a/integration_tests/suite/helpers/config.py +++ b/integration_tests/suite/helpers/config.py @@ -6,11 +6,7 @@ from wazo_dird import database -from .constants import ( - MAIN_TENANT, - SUB_TENANT, - TENANT_UUID_2, -) +from .constants import MAIN_TENANT, SUB_TENANT, TENANT_UUID_2 def _random_string(n): @@ -29,7 +25,6 @@ def _random_string(n): class Config: - def __init__(self, Session): self.display_crud = database.DisplayCRUD(Session) self.profile_crud = database.ProfileCRUD(Session) @@ -142,7 +137,12 @@ def new_conference_config(Session): config.with_source( backend='conference', name='confs', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['name'], ) @@ -150,7 +150,12 @@ def new_conference_config(Session): tenant_uuid=SUB_TENANT, backend='conference', name='confs_sub', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['name'], ) @@ -176,7 +181,12 @@ def new_csv_with_multiple_displays_config(Session): config.with_display( name='second_display', columns=[ - {'title': 'fn', 'default': 'Unknown', 'field': 'firstname', 'type': 'firstname'}, + { + 'title': 'fn', + 'default': 'Unknown', + 'field': 'firstname', + 'type': 'firstname', + }, {'title': 'ln', 'default': 'Unknown', 'field': 'lastname'}, {'title': 'Empty', 'field': 'not_there'}, {'type': 'status'}, @@ -195,7 +205,7 @@ def new_csv_with_multiple_displays_config(Session): 'lastname': "{ln}", 'firstname': "{fn}", 'number': "{num}", - 'reverse': '{fn} {ln}' + 'reverse': '{fn} {ln}', }, ) config.with_source( @@ -211,8 +221,8 @@ def new_csv_with_multiple_displays_config(Session): 'lastname': "{ln}", 'firstname': "{fn}", 'number': "{num}", - 'reverse': '{fn} {ln}' - } + 'reverse': '{fn} {ln}', + }, ) config.with_profile( name='default', @@ -243,11 +253,7 @@ def new_csv_with_pipes_config(Session): file='/tmp/data/test.csv', separator="|", searched_columns=['fn', 'ln'], - format_columns={ - 'lastname': "{ln}", - 'firstname': "{fn}", - 'number': "{num}", - }, + format_columns={'lastname': "{ln}", 'firstname': "{fn}", 'number': "{num}"}, ) config.with_profile( name='default', @@ -275,11 +281,7 @@ def new_half_broken_config(Session): separator="|", unique_column='id', searched_columns=['fn', 'ln'], - format_columns={ - 'lastname': "{ln}", - 'firstname': "{fn}", - 'number': "{num}", - }, + format_columns={'lastname': "{ln}", 'firstname': "{fn}", 'number': "{num}"}, ) config.with_source( backend='csv', @@ -287,16 +289,9 @@ def new_half_broken_config(Session): file='/tmp/data/test.csv', separator="|", searched_columns=['fn', 'ln'], - format_columns={ - 'lastname': "{ln}", - 'firstname': "{fn}", - 'number': "{num}", - } - ) - config.with_source( - backend='broken', - name='broken', + format_columns={'lastname': "{ln}", 'firstname': "{fn}", 'number': "{num}"}, ) + config.with_source(backend='broken', name='broken') return config @@ -318,7 +313,7 @@ def new_ldap_config(Session): 'lastname': "{sn}", 'number': "{telephoneNumber}", 'reverse': "{cn}", - } + }, ) config.with_profile( name='default', @@ -351,7 +346,7 @@ def new_ldap_city_config(Session): 'lastname': "{sn}", 'number': "{telephoneNumber}", 'reverse': "{cn}", - } + }, ) config.with_profile( name='default', @@ -379,7 +374,7 @@ def new_ldap_service_down_config(Session): 'lastname': "{sn}", 'number': "{telephoneNumber}", 'reverse': "{cn}", - } + }, ) config.with_profile( name='default', @@ -407,7 +402,7 @@ def new_ldap_service_innactive_config(Session): 'lastname': "{sn}", 'number': "{telephoneNumber}", 'reverse': "{cn}", - } + }, ) config.with_profile( name='default', @@ -454,18 +449,9 @@ def new_multiple_sources_config(Session): file='/tmp/data/other.csv', unique_column='clientno', separator=',', - searched_columns=[ - 'firstname', - 'lastname', - 'number', - ], - first_matched_columns=[ - 'number', - 'mobile', - ], - format_columns={ - 'reverse': "{firstname} {lastname}", - }, + searched_columns=['firstname', 'lastname', 'number'], + first_matched_columns=['number', 'mobile'], + format_columns={'reverse': "{firstname} {lastname}"}, ) config.with_profile( name='default', @@ -490,7 +476,11 @@ def new_personal_only_config(Session): columns=[ {'title': 'Firstname', 'field': 'firstname'}, {'title': 'Lastname', 'field': 'lastname'}, - {'title': 'Number', 'field': 'number', 'number_display': '{firstname} {lastname}'}, + { + 'title': 'Number', + 'field': 'number', + 'number_display': '{firstname} {lastname}', + }, {'title': 'Favorite', 'type': 'favorite'}, ], ) @@ -519,7 +509,9 @@ def new_phone_config(Session): config = Config(Session) config.with_display( name='default', - columns=[{'field': 'phone', 'type': 'number', 'number_display': '{display_name}'}], + columns=[ + {'field': 'phone', 'type': 'number', 'number_display': '{display_name}'} + ], ) config.with_display( name='test_fallback', @@ -564,7 +556,9 @@ def new_phone_view_config(Session): config = Config(Session) config.with_display( name='default', - columns=[{'field': 'phone', 'type': 'number', 'number_display': '{display_name}'}], + columns=[ + {'field': 'phone', 'type': 'number', 'number_display': '{display_name}'} + ], ) config.with_source( backend='csv', @@ -581,7 +575,7 @@ def new_phone_view_config(Session): config.with_profile( name='default', display='default', - services={'lookup': {'sources': ['test_csv']}} + services={'lookup': {'sources': ['test_csv']}}, ) return config @@ -600,7 +594,12 @@ def new_wazo_users_config(Session): config.with_source( backend='wazo', name='wazo_america', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) @@ -625,21 +624,36 @@ def new_wazo_users_multiple_wazo_config(Session): config.with_source( backend='wazo', name='wazo_asia', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'asia', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) config.with_source( backend='wazo', name='wazo_america', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) config.with_source( backend='wazo', name='wazo_europe', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'europe', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) @@ -647,7 +661,12 @@ def new_wazo_users_multiple_wazo_config(Session): tenant_uuid=SUB_TENANT, backend='wazo', name='wazo_america_sub', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) @@ -675,16 +694,10 @@ def new_multi_source_profile(Session): columns=[{'title': 'Firstname', 'field': 'firstname'}], ) config.with_source( - backend='csv', - tenant_uuid=MAIN_TENANT, - name='csv_main', - file='/tmp/test.csv', + backend='csv', tenant_uuid=MAIN_TENANT, name='csv_main', file='/tmp/test.csv' ) config.with_source( - backend='csv', - tenant_uuid=SUB_TENANT, - name='csv_sub', - file='/tmp/test.csv', + backend='csv', tenant_uuid=SUB_TENANT, name='csv_sub', file='/tmp/test.csv' ) config.with_source( backend='personal', @@ -693,16 +706,18 @@ def new_multi_source_profile(Session): db_uri='db_uri', ) config.with_source( - backend='personal', - tenant_uuid=SUB_TENANT, - name='personal_sub', - db_uri='db_uri', + backend='personal', tenant_uuid=SUB_TENANT, name='personal_sub', db_uri='db_uri' ) config.with_source( backend='wazo', name='a_wazo_main', tenant_uuid=MAIN_TENANT, - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'asia', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) @@ -710,7 +725,12 @@ def new_multi_source_profile(Session): backend='wazo', tenant_uuid=SUB_TENANT, name='wazo_sub', - auth={'host': 'auth', 'username': 'foo', 'password': 'bar', 'verify_certificate': False}, + auth={ + 'host': 'auth', + 'username': 'foo', + 'password': 'bar', + 'verify_certificate': False, + }, confd={'host': 'america', 'port': 9486, 'https': False}, searched_columns=['firstname', 'lastname'], ) diff --git a/integration_tests/suite/helpers/constants.py b/integration_tests/suite/helpers/constants.py index 3633859d..2a2ebb04 100644 --- a/integration_tests/suite/helpers/constants.py +++ b/integration_tests/suite/helpers/constants.py @@ -5,7 +5,9 @@ ASSET_ROOT = os.path.join(os.path.dirname(__file__), '..', '..', 'assets') CA_CERT = os.path.join(ASSET_ROOT, 'ssl', 'dird', 'server.crt') -DB_URI_FMT = os.getenv('DB_URI', 'postgresql://asterisk:proformatique@localhost:{port}/asterisk') +DB_URI_FMT = os.getenv( + 'DB_URI', 'postgresql://asterisk:proformatique@localhost:{port}/asterisk' +) VALID_UUID = 'uuid-tenant-master' VALID_UUID_1 = 'uuid-1' VALID_TOKEN_1 = 'valid-token-1' @@ -24,7 +26,7 @@ {'title': 'Lastname', 'field': 'lastname'}, {'title': 'Number', 'field': 'number'}, ], - }, + } ] TENANT_UUID_2 = '4c3c6c6f-7dda-4561-9cc0-a2d757c725dd' UNKNOWN_UUID = '00000000-0000-0000-0000-000000000000' diff --git a/integration_tests/suite/helpers/fixtures/db.py b/integration_tests/suite/helpers/fixtures/db.py index 6dcbac10..a782effd 100644 --- a/integration_tests/suite/helpers/fixtures/db.py +++ b/integration_tests/suite/helpers/fixtures/db.py @@ -35,7 +35,9 @@ def wrapper(self, *args, **kwargs): except exception.NoSuchDisplay: pass return result + return wrapper + return decorator @@ -57,7 +59,9 @@ def wrapper(self, *args, **kwargs): except exception.NoSuchProfileAPIException: pass return result + return wrapper + return decorator @@ -78,9 +82,13 @@ def wrapper(self, *args, **kwargs): result = decorated(self, source, *args, **kwargs) finally: try: - self.source_crud.delete(backend, source['uuid'], visible_tenants=None) + self.source_crud.delete( + backend, source['uuid'], visible_tenants=None + ) except exception.NoSuchSource: pass return result + return wrapper + return decorator diff --git a/integration_tests/suite/helpers/fixtures/http.py b/integration_tests/suite/helpers/fixtures/http.py index 8db999c8..9ae34801 100644 --- a/integration_tests/suite/helpers/fixtures/http.py +++ b/integration_tests/suite/helpers/fixtures/http.py @@ -20,7 +20,6 @@ def conference_source(**source_args): source_args.setdefault('token', VALID_TOKEN_MAIN_TENANT) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -36,13 +35,14 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator def csv_source(**source_args): def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): source_args.setdefault('name', random_string()) @@ -62,7 +62,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -71,7 +73,6 @@ def csv_ws_source(**source_args): source_args.setdefault('token', VALID_TOKEN_MAIN_TENANT) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -87,7 +88,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -97,7 +100,6 @@ def display(**display_args): display_args.setdefault('columns', [{'field': 'fn'}]) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(display_args['token']) @@ -113,7 +115,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -123,7 +127,6 @@ def ldap_source(**source_args): source_args.setdefault('ldap_base_dn', 'ou=people,dc=example,dc=org') def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -139,7 +142,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -147,7 +152,6 @@ def personal_source(**source_args): source_args.setdefault('token', VALID_TOKEN_MAIN_TENANT) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -163,7 +167,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -171,7 +177,6 @@ def phonebook_source(**source_args): source_args.setdefault('token', VALID_TOKEN_MAIN_TENANT) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -187,7 +192,9 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator @@ -196,7 +203,6 @@ def wazo_source(**source_args): source_args.setdefault('token', VALID_TOKEN_MAIN_TENANT) def decorator(decorated): - @wraps(decorated) def wrapper(self, *args, **kwargs): client = self.get_client(source_args['token']) @@ -212,5 +218,7 @@ def wrapper(self, *args, **kwargs): if status_code != 404: raise return result + return wrapper + return decorator diff --git a/integration_tests/suite/test_authentication.py b/integration_tests/suite/test_authentication.py index 8b3da3b7..70671fc4 100644 --- a/integration_tests/suite/test_authentication.py +++ b/integration_tests/suite/test_authentication.py @@ -1,18 +1,11 @@ # Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - contains_string, - equal_to, -) +from hamcrest import assert_that, contains_string, equal_to from .helpers.base import BaseDirdIntegrationTest from .helpers.config import new_auth_only_config -from .helpers.constants import ( - VALID_TOKEN_MAIN_TENANT, - VALID_TOKEN_NO_ACL, -) +from .helpers.constants import VALID_TOKEN_MAIN_TENANT, VALID_TOKEN_NO_ACL class TestAuthentication(BaseDirdIntegrationTest): @@ -49,9 +42,10 @@ def test_no_auth_server_gives_503(self): result = self.get_headers_result('default', token=VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(503)) - assert_that(result.json()['reason'][0], contains_string( - 'Authentication server unreachable', - )) + assert_that( + result.json()['reason'][0], + contains_string('Authentication server unreachable'), + ) class TestAuthenticationCoverage(BaseDirdIntegrationTest): @@ -74,7 +68,9 @@ def test_auth_on_lookup(self): def test_auth_on_reverse(self): result_1 = self.get_reverse_result('exten', 'default', 'uuid') - result_2 = self.get_reverse_result('exten', 'default', 'uuid', VALID_TOKEN_NO_ACL) + result_2 = self.get_reverse_result( + 'exten', 'default', 'uuid', VALID_TOKEN_NO_ACL + ) assert_that(result_1.status_code, equal_to(401)) assert_that(result_2.status_code, equal_to(401)) @@ -158,21 +154,27 @@ def test_auth_on_personal_list_with_profile(self): def test_auth_on_menu_cisco(self): result_1 = self.get_menu_cisco_result('default', 'uuid') - result_2 = self.get_menu_cisco_result('default', 'uuid', token=VALID_TOKEN_NO_ACL) + result_2 = self.get_menu_cisco_result( + 'default', 'uuid', token=VALID_TOKEN_NO_ACL + ) assert_that(result_1.status_code, equal_to(401)) assert_that(result_2.status_code, equal_to(401)) def test_auth_on_input_cisco(self): result_1 = self.get_input_cisco_result('default', 'uuid') - result_2 = self.get_input_cisco_result('default', 'uuid', token=VALID_TOKEN_NO_ACL) + result_2 = self.get_input_cisco_result( + 'default', 'uuid', token=VALID_TOKEN_NO_ACL + ) assert_that(result_1.status_code, equal_to(401)) assert_that(result_2.status_code, equal_to(401)) def test_auth_on_lookup_cisco(self): result_1 = self.get_lookup_cisco_result('default', 'uuid') - result_2 = self.get_lookup_cisco_result('default', 'uuid', token=VALID_TOKEN_NO_ACL) + result_2 = self.get_lookup_cisco_result( + 'default', 'uuid', token=VALID_TOKEN_NO_ACL + ) assert_that(result_1.status_code, equal_to(401)) assert_that(result_2.status_code, equal_to(401)) diff --git a/integration_tests/suite/test_auto_create.py b/integration_tests/suite/test_auto_create.py index 680b5d2e..31475d79 100644 --- a/integration_tests/suite/test_auto_create.py +++ b/integration_tests/suite/test_auto_create.py @@ -11,18 +11,12 @@ has_entries, has_item, ) -from xivo_bus import ( - Publisher, - Marshaler, -) +from xivo_bus import Publisher, Marshaler from xivo_bus.resources.auth.events import TenantCreatedEvent from xivo_test_helpers import until from xivo_test_helpers.hamcrest.uuid_ import uuid_ from xivo_test_helpers.bus import BusClient -from xivo_test_helpers.auth import ( - AuthClient as MockAuthClient, - MockUserToken, -) +from xivo_test_helpers.auth import AuthClient as MockAuthClient, MockUserToken from .helpers.base import BaseDirdIntegrationTest from .helpers.constants import SUB_TENANT @@ -40,17 +34,18 @@ def setUp(self): bus = BusClient.from_connection_fields(host='localhost', port=bus_port) until.true(bus.is_up, timeout=5) - bus_url = 'amqp://{username}:{password}@{host}:{port}//'.format(username='guest', - password='guest', - host='localhost', - port=bus_port) + bus_url = 'amqp://{username}:{password}@{host}:{port}//'.format( + username='guest', password='guest', host='localhost', port=bus_port + ) connection = kombu.Connection(bus_url) connection.connect() marshaler = Marshaler('the-xivo-uuid') exchange = kombu.Exchange('xivo', type='topic') producer = kombu.Producer(connection, exchange=exchange, auto_declare=True) self.publisher = Publisher(producer, marshaler) - self.mock_auth_client = MockAuthClient('localhost', self.service_port(9497, 'auth')) + self.mock_auth_client = MockAuthClient( + 'localhost', self.service_port(9497, 'auth') + ) def wait_for_dird_bus_connection(): response = self.client.status.get() @@ -63,47 +58,64 @@ def test_conference_source(self): def check(): response = self.client.conference_source.list(tenant_uuid=self.tenant_uuid) - assert_that(response, has_entries(items=has_item( + key_file = '/var/lib/wazo-auth-keys/wazo-dird-conference-backend-key.yml' + assert_that( + response, has_entries( - uuid=uuid_(), - tenant_uuid=self.tenant_uuid, - name='auto_conference_mytenant', - auth={ - 'host': 'localhost', - 'port': 9497, - 'verify_certificate': '/usr/share/xivo-certs/server.crt', - 'version': '0.1', - 'key_file': '/var/lib/wazo-auth-keys/wazo-dird-conference-backend-key.yml', - }, - confd={ - 'host': 'localhost', - 'port': 9486, - 'verify_certificate': '/usr/share/xivo-certs/server.crt', - 'version': '1.1', - 'https': True, - }, - first_matched_columns=empty(), - searched_columns=contains_inanyorder('name', 'extensions', 'incalls'), - format_columns={'phone': '{extensions[0]}'}, + items=has_item( + has_entries( + uuid=uuid_(), + tenant_uuid=self.tenant_uuid, + name='auto_conference_mytenant', + auth={ + 'host': 'localhost', + 'port': 9497, + 'verify_certificate': '/usr/share/xivo-certs/server.crt', + 'version': '0.1', + 'key_file': key_file, + }, + confd={ + 'host': 'localhost', + 'port': 9486, + 'verify_certificate': '/usr/share/xivo-certs/server.crt', + 'version': '1.1', + 'https': True, + }, + first_matched_columns=empty(), + searched_columns=contains_inanyorder( + 'name', 'extensions', 'incalls' + ), + format_columns={'phone': '{extensions[0]}'}, + ) + ) ), - ))) + ) until.assert_(check, timeout=3) - for source in self.client.conference_source.list(tenant_uuid=self.tenant_uuid)['items']: + for source in self.client.conference_source.list(tenant_uuid=self.tenant_uuid)[ + 'items' + ]: if source['name'] == 'auto_conference_mytenant': conference_uuid = source['uuid'] def check(): - response = self.client.profiles.list(name='default', tenant_uuid=self.tenant_uuid) - assert_that(response, has_entries(items=has_item( + response = self.client.profiles.list( + name='default', tenant_uuid=self.tenant_uuid + ) + assert_that( + response, has_entries( - services=has_entries( - lookup=has_entries( - sources=has_item(has_entries(uuid=conference_uuid)), - ), - ), + items=has_item( + has_entries( + services=has_entries( + lookup=has_entries( + sources=has_item(has_entries(uuid=conference_uuid)) + ) + ) + ) + ) ), - ))) + ) until.assert_(check, timeout=3) @@ -113,44 +125,36 @@ def test_lookup(self): def check(): result = self.lookup('alice', 'default', token=token) - assert_that(result, has_entries( - column_headers=contains( - 'Nom', - 'Numéro', - 'Mobile', - 'Boîte vocale', - 'Favoris', - 'E-mail', - ), - column_types=contains( - 'name', - 'number', - 'number', - 'voicemail', - 'favorite', - 'email', - ), - results=contains_inanyorder(has_entries( - column_values=contains( - 'Alice', - '1234', - None, - None, - False, - None, + assert_that( + result, + has_entries( + column_headers=contains( + 'Nom', 'Numéro', 'Mobile', 'Boîte vocale', 'Favoris', 'E-mail' + ), + column_types=contains( + 'name', 'number', 'number', 'voicemail', 'favorite', 'email' ), - )), - )) + results=contains_inanyorder( + has_entries( + column_values=contains( + 'Alice', '1234', None, None, False, None + ) + ) + ), + ), + ) with self.personal({'firstname': 'Alice', 'number': '1234'}, token=token): until.assert_(check, timeout=3) def _create_user(self): - self.mock_auth_client.set_tenants({ - 'total': 1, - 'filtered': 1, - 'items': [{'uuid': self.tenant_uuid, 'name': self.tenant_name}], - }) + self.mock_auth_client.set_tenants( + { + 'total': 1, + 'filtered': 1, + 'items': [{'uuid': self.tenant_uuid, 'name': self.tenant_name}], + } + ) token = MockUserToken.some_token(metadata={'tenant_uuid': self.tenant_uuid}) self.mock_auth_client.set_token(token) return token.token_id diff --git a/integration_tests/suite/test_backends.py b/integration_tests/suite/test_backends.py index 4799e501..35b3d3ee 100644 --- a/integration_tests/suite/test_backends.py +++ b/integration_tests/suite/test_backends.py @@ -1,12 +1,7 @@ # Copyright 2018-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - has_entries, -) +from hamcrest import assert_that, contains, contains_inanyorder, has_entries from .helpers.base import BaseDirdIntegrationTest @@ -19,11 +14,13 @@ def test_list(self): result = self.client.backends.list() # not sample which is disabled # not unknown which is not installed - expected = ['csv', 'csv_ws', 'ldap', 'personal', 'phonebook', 'wazo'] + expected = ['csv', 'csv_ws', 'ldap', 'personal', 'phonebook', 'wazo'] self._assert_matches(result, 6, 6, contains_inanyorder, *expected) result = self.client.backends.list(search='a') - self._assert_matches(result, 6, 3, contains_inanyorder, 'ldap', 'personal', 'wazo') + self._assert_matches( + result, 6, 3, contains_inanyorder, 'ldap', 'personal', 'wazo' + ) result = self.client.backends.list(name='csv') self._assert_matches(result, 6, 1, contains, 'csv') @@ -52,8 +49,6 @@ def _assert_matches(result, total, filtered, matcher, *names): has_entries( total=total, filtered=filtered, - items=matcher( - *[has_entries(name=name) for name in names] - ) - ) + items=matcher(*[has_entries(name=name) for name in names]), + ), ) diff --git a/integration_tests/suite/test_conference_backend.py b/integration_tests/suite/test_conference_backend.py index 7c173900..0a8de464 100644 --- a/integration_tests/suite/test_conference_backend.py +++ b/integration_tests/suite/test_conference_backend.py @@ -1,20 +1,11 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - empty, - has_entries, -) +from hamcrest import assert_that, contains, contains_inanyorder, empty, has_entries from mock import Mock from .base_dird_integration_test import BackendWrapper -from .helpers.base import ( - BaseDirdIntegrationTest, - DirdAssetRunningTestCase, -) +from .helpers.base import BaseDirdIntegrationTest, DirdAssetRunningTestCase from .helpers.config import new_conference_config from .helpers.constants import MAIN_TENANT @@ -49,10 +40,7 @@ def setUp(self): 'reverse': '{name}', }, } - dependencies = { - 'api': Mock(), - 'config': config, - } + dependencies = {'api': Mock(), 'config': config} self.backend = BackendWrapper('conference', dependencies) def tearDown(self): @@ -61,21 +49,59 @@ def tearDown(self): def test_lookup_by_name(self): result = self.backend.search('daily') - assert_that(result, contains( - has_entries( - displayname='daily scrum', - extensions=contains('4002'), - id=4, - incalls=empty(), - name='daily scrum', - phone='4002', - reverse='daily scrum', + assert_that( + result, + contains( + has_entries( + displayname='daily scrum', + extensions=contains('4002'), + id=4, + incalls=empty(), + name='daily scrum', + phone='4002', + reverse='daily scrum', + ) ), - )) + ) def test_lookup_by_extension(self): result = self.backend.search('4002') - assert_that(result, contains( + assert_that( + result, + contains( + has_entries( + displayname='daily scrum', + extensions=contains('4002'), + id=4, + incalls=empty(), + name='daily scrum', + phone='4002', + reverse='daily scrum', + ) + ), + ) + + def test_lookup_by_incall(self): + result = self.backend.search('1009') + assert_that( + result, + contains( + has_entries( + displayname='test', + extensions=contains('4001'), + id=1, + incalls=contains('1009'), + name='test', + phone='4001', + reverse='test', + ) + ), + ) + + def test_reverse_lookup_on_exten(self): + result = self.backend.first('4002') + assert_that( + result, has_entries( displayname='daily scrum', extensions=contains('4002'), @@ -85,11 +111,12 @@ def test_lookup_by_extension(self): phone='4002', reverse='daily scrum', ), - )) + ) - def test_lookup_by_incall(self): - result = self.backend.search('1009') - assert_that(result, contains( + def test_reverse_lookup_on_incall(self): + result = self.backend.first('1009') + assert_that( + result, has_entries( displayname='test', extensions=contains('4001'), @@ -99,38 +126,17 @@ def test_lookup_by_incall(self): phone='4001', reverse='test', ), - )) - - def test_reverse_lookup_on_exten(self): - result = self.backend.first('4002') - assert_that(result, has_entries( - displayname='daily scrum', - extensions=contains('4002'), - id=4, - incalls=empty(), - name='daily scrum', - phone='4002', - reverse='daily scrum', - )) - - def test_reverse_lookup_on_incall(self): - result = self.backend.first('1009') - assert_that(result, has_entries( - displayname='test', - extensions=contains('4001'), - id=1, - incalls=contains('1009'), - name='test', - phone='4001', - reverse='test', - )) + ) def test_favorites(self): result = self.backend.list(['1', '4'], None) - assert_that(result, contains_inanyorder( - has_entries(id=4, displayname='daily scrum'), - has_entries(id=1, displayname='test'), - )) + assert_that( + result, + contains_inanyorder( + has_entries(id=4, displayname='daily scrum'), + has_entries(id=1, displayname='test'), + ), + ) class TestNoConfd(BaseDirdIntegrationTest): diff --git a/integration_tests/suite/test_conference_contacts.py b/integration_tests/suite/test_conference_contacts.py index 520a24ad..c42a346e 100644 --- a/integration_tests/suite/test_conference_contacts.py +++ b/integration_tests/suite/test_conference_contacts.py @@ -1,11 +1,7 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - calling, - has_properties, -) +from hamcrest import assert_that, calling, has_properties from xivo_test_helpers.hamcrest.raises import raises @@ -29,7 +25,9 @@ class TestConferenceContactList(BaseDirdIntegrationTest): def setUp(self): super().setUp() - for source in self.client.sources.list(backend='conference', recurse=True)['items']: + for source in self.client.sources.list(backend='conference', recurse=True)[ + 'items' + ]: if source['name'] == 'confs': self.source_uuid = source['uuid'] elif source['name'] == 'confs_sub': @@ -38,7 +36,9 @@ def setUp(self): def test_with_an_unknown_source(self): assert_that( calling(self.contacts).with_args(self.client, UNKNOWN_UUID), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) def test_multi_tenant(self): @@ -47,25 +47,27 @@ def test_multi_tenant(self): assert_that( calling(self.contacts).with_args(sub_tenant_client, self.source_uuid), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(self.contacts).with_args( - sub_tenant_client, - self.source_uuid, - tenant_uuid=MAIN_TENANT + sub_tenant_client, self.source_uuid, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) assert_that( calling(self.contacts).with_args( - main_tenant_client, - self.source_uuid, - tenant_uuid=SUB_TENANT, + main_tenant_client, self.source_uuid, tenant_uuid=SUB_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) def test_with_no_confd(self): @@ -73,17 +75,14 @@ def test_with_no_confd(self): try: assert_that( calling(self.contacts).with_args(self.client, self.source_uuid), - raises(Exception).matching(has_properties( - response=has_properties(status_code=503), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=503)) + ), ) finally: self.start_service('america') def contacts(self, client, uuid, *args, **kwargs): return client.backends.list_contacts_from_source( - backend=BACKEND, - source_uuid=uuid, - *args, - **kwargs + backend=BACKEND, source_uuid=uuid, *args, **kwargs ) diff --git a/integration_tests/suite/test_conference_http.py b/integration_tests/suite/test_conference_http.py index 949bb864..0b4ccf28 100644 --- a/integration_tests/suite/test_conference_http.py +++ b/integration_tests/suite/test_conference_http.py @@ -35,12 +35,7 @@ class BaseConferenceCRUDTestCase(BaseDirdIntegrationTest): asset = 'all_routes' - valid_body = { - 'name': 'conferences', - 'auth': { - 'key_file': '/path/to/the/key/file', - } - } + valid_body = {'name': 'conferences', 'auth': {'key_file': '/path/to/the/key/file'}} @contextmanager def source(self, client, *args, **kwargs): @@ -52,13 +47,12 @@ def source(self, client, *args, **kwargs): class TestDelete(BaseConferenceCRUDTestCase): - @fixtures.conference_source() def test_delete(self, source): self.client.conference_source.delete(source['uuid']) assert_that( calling(self.client.conference_source.get).with_args(source['uuid']), - raises(Exception).matching(HTTP_404) + raises(Exception).matching(HTTP_404), ) assert_that( @@ -79,14 +73,14 @@ def test_delete_multi_tenant(self, sub, main): assert_that( calling(sub_client.conference_source.delete).with_args( - main['uuid'], tenant_uuid=MAIN_TENANT, + main['uuid'], tenant_uuid=MAIN_TENANT ), raises(Exception).matching(HTTP_401), ) assert_that( calling(main_client.conference_source.delete).with_args( - main['uuid'], tenant_uuid=SUB_TENANT, + main['uuid'], tenant_uuid=SUB_TENANT ), raises(Exception).matching(HTTP_404), ) @@ -98,7 +92,6 @@ def test_delete_multi_tenant(self, sub, main): class TestGet(BaseConferenceCRUDTestCase): - @fixtures.conference_source() def test_get(self, source): response = self.client.conference_source.get(source['uuid']) @@ -106,7 +99,7 @@ def test_get(self, source): assert_that( calling(self.client.conference_source.get).with_args(UNKNOWN_UUID), - raises(Exception).matching(HTTP_404) + raises(Exception).matching(HTTP_404), ) @fixtures.conference_source(token=VALID_TOKEN_MAIN_TENANT) @@ -120,7 +113,7 @@ def test_get_multi_tenant(self, sub, main): assert_that( calling(main_client.conference_source.get).with_args( - main['uuid'], tenant_uuid=SUB_TENANT, + main['uuid'], tenant_uuid=SUB_TENANT ), raises(Exception).matching(HTTP_404), ) @@ -132,52 +125,35 @@ def test_get_multi_tenant(self, sub, main): assert_that( calling(sub_client.conference_source.get).with_args( - main['uuid'], tenant_uuid=MAIN_TENANT, + main['uuid'], tenant_uuid=MAIN_TENANT ), raises(Exception).matching(HTTP_401), ) class TestList(BaseConferenceCRUDTestCase): - @fixtures.conference_source(name='abc') @fixtures.conference_source(name='bcd') @fixtures.conference_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.conference_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.conference_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.conference_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) assert_that( self.client.conference_source.list(search='b'), - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=3, filtered=2), ) @fixtures.conference_source(name='abc') @@ -186,38 +162,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.conference_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.conference_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.conference_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.conference_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.conference_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -229,57 +189,38 @@ def test_multi_tenant(self, c, b, a): assert_that( main_client.conference_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_client.conference_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( main_client.conference_source.list(tenant_uuid=SUB_TENANT), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_client.conference_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_client.conference_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( - calling(sub_client.conference_source.list).with_args(tenant_uuid=MAIN_TENANT), + calling(sub_client.conference_source.list).with_args( + tenant_uuid=MAIN_TENANT + ), raises(Exception).matching(HTTP_401), ) class TestPost(BaseConferenceCRUDTestCase): - def test_post(self): try: self.client.conference_source.create({}) @@ -298,10 +239,12 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( - calling(self.client.conference_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + calling(self.client.conference_source.create).with_args( + self.valid_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -311,28 +254,33 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.conference_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.conference_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.conference_source.create).with_args(self.valid_body), + calling(sub_tenant_client.conference_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BaseConferenceCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { @@ -340,22 +288,24 @@ def setUp(self): 'auth': {'username': 'foo', 'password': 'secret'}, 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.conference_source(name='foobar') @fixtures.conference_source(name='other') def test_put(self, foobar, other): assert_that( - calling(self.client.conference_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(HTTP_409) + calling(self.client.conference_source.edit).with_args( + foobar['uuid'], other + ), + raises(Exception).matching(HTTP_409), ) assert_that( - calling(self.client.conference_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(HTTP_404) + calling(self.client.conference_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching(HTTP_404), ) try: @@ -374,7 +324,9 @@ def test_put(self, foobar, other): self.fail('Should have raised') assert_that( - calling(self.client.conference_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.conference_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -389,7 +341,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.conference_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -404,25 +356,29 @@ def test_put_multi_tenant(self, sub, main): ) assert_that( - calling(sub_client.conference_source.edit).with_args(main['uuid'], self.new_body), + calling(sub_client.conference_source.edit).with_args( + main['uuid'], self.new_body + ), raises(Exception).matching(HTTP_404), ) assert_that( calling(sub_client.conference_source.edit).with_args( - main['uuid'], self.new_body, tenant_uuid=MAIN_TENANT, + main['uuid'], self.new_body, tenant_uuid=MAIN_TENANT ), raises(Exception).matching(HTTP_401), ) assert_that( calling(main_client.conference_source.edit).with_args( - main['uuid'], self.new_body, tenant_uuid=SUB_TENANT, + main['uuid'], self.new_body, tenant_uuid=SUB_TENANT ), raises(Exception).matching(HTTP_404), ) assert_that( - calling(main_client.conference_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_client.conference_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) diff --git a/integration_tests/suite/test_config_view.py b/integration_tests/suite/test_config_view.py index bdea2d8b..d6e92a34 100644 --- a/integration_tests/suite/test_config_view.py +++ b/integration_tests/suite/test_config_view.py @@ -14,6 +14,9 @@ class TestConfigView(BaseDirdIntegrationTest): def test_get_config(self): result = self.get_config(token=VALID_TOKEN_MAIN_TENANT) - assert_that(result, has_entries({'foo': {'bar': 'main', - 'baz': 'conf.d', - 'other': 'overwritten'}})) + assert_that( + result, + has_entries( + {'foo': {'bar': 'main', 'baz': 'conf.d', 'other': 'overwritten'}} + ), + ) diff --git a/integration_tests/suite/test_core_functionality.py b/integration_tests/suite/test_core_functionality.py index a34e9d5d..37499886 100644 --- a/integration_tests/suite/test_core_functionality.py +++ b/integration_tests/suite/test_core_functionality.py @@ -18,22 +18,19 @@ CSVWithMultipleDisplayTestCase, HalfBrokenTestCase, ) -from .helpers.config import ( - new_multiple_sources_config, -) +from .helpers.config import new_multiple_sources_config -from .helpers.constants import ( - VALID_TOKEN_MAIN_TENANT, - VALID_UUID, -) +from .helpers.constants import VALID_TOKEN_MAIN_TENANT, VALID_UUID -EMPTY_RELATIONS = {'xivo_id': None, - 'user_id': None, - 'user_uuid': None, - 'endpoint_id': None, - 'agent_id': None, - 'source_entry_id': None} +EMPTY_RELATIONS = { + 'xivo_id': None, + 'user_id': None, + 'user_uuid': None, + 'endpoint_id': None, + 'agent_id': None, + 'source_entry_id': None, +} class BaseMultipleSourceLauncher(BaseDirdIntegrationTest): @@ -43,83 +40,101 @@ class BaseMultipleSourceLauncher(BaseDirdIntegrationTest): class TestSourceModification(BaseMultipleSourceLauncher): - def test_source_update(self): response = self.lookup('alan', 'default') - assert_that(response, has_entries(results=contains( - has_entries(column_values=contains( - 'Alice', - 'Alan', - '1111', - )) - ))) + assert_that( + response, + has_entries( + results=contains( + has_entries(column_values=contains('Alice', 'Alan', '1111')) + ) + ), + ) source = self.client.csv_source.list(name='third_csv')['items'][0] source['format_columns']['firstname'] = 'SUCCESS {firstname}' self.client.csv_source.edit(source['uuid'], source) response = self.lookup('alan', 'default') - assert_that(response, has_entries(results=contains( - has_entries(column_values=contains( - 'SUCCESS Alice', - 'Alan', - '1111', - )) - ))) + assert_that( + response, + has_entries( + results=contains( + has_entries(column_values=contains('SUCCESS Alice', 'Alan', '1111')) + ) + ), + ) class TestCoreSourceManagement(BaseMultipleSourceLauncher): - alice_aaa = {'column_values': ['Alice', 'AAA', '5555555555'], - 'source': 'my_csv', - 'backend': 'csv', - 'relations': EMPTY_RELATIONS} - alice_alan = {'column_values': ['Alice', 'Alan', '1111'], - 'source': 'third_csv', - 'backend': 'csv', - 'relations': {'xivo_id': None, - 'user_id': None, - 'user_uuid': None, - 'endpoint_id': None, - 'agent_id': None, - 'source_entry_id': '1'}} + alice_aaa = { + 'column_values': ['Alice', 'AAA', '5555555555'], + 'source': 'my_csv', + 'backend': 'csv', + 'relations': EMPTY_RELATIONS, + } + alice_alan = { + 'column_values': ['Alice', 'Alan', '1111'], + 'source': 'third_csv', + 'backend': 'csv', + 'relations': { + 'xivo_id': None, + 'user_id': None, + 'user_uuid': None, + 'endpoint_id': None, + 'agent_id': None, + 'source_entry_id': '1', + }, + } def test_multiple_source_from_the_same_backend(self): result = self.lookup('lice', 'default') # second_csv does not search in column firstname - assert_that(result['results'], contains_inanyorder(self.alice_aaa, self.alice_alan)) + assert_that( + result['results'], contains_inanyorder(self.alice_aaa, self.alice_alan) + ) class TestReverse(BaseMultipleSourceLauncher): - def setUp(self): super().setUp() - self.alice_expected_fields = {'clientno': '1', - 'firstname': 'Alice', - 'lastname': 'Alan', - 'number': '1111', - 'mobile': '11112', - 'reverse': 'Alice Alan'} - self.qwerty_expected_fields = {'fn': 'qwerty', - 'ln': 'azerty', - 'num': '1111', - 'firstname': 'qwerty', - 'lastname': 'azerty', - 'number': '1111', - 'reverse': 'qwerty azerty'} - self.alice_result = {'display': 'Alice Alan', - 'exten': '1111', - 'source': 'third_csv', - 'fields': self.alice_expected_fields} - self.qwerty_result_1 = {'display': 'qwerty azerty', - 'exten': '1111', - 'source': 'my_csv', - 'fields': self.qwerty_expected_fields} - self.qwerty_result_2 = {'display': 'qwerty azerty', - 'exten': '1111', - 'source': 'second_csv', - 'fields': self.qwerty_expected_fields} + self.alice_expected_fields = { + 'clientno': '1', + 'firstname': 'Alice', + 'lastname': 'Alan', + 'number': '1111', + 'mobile': '11112', + 'reverse': 'Alice Alan', + } + self.qwerty_expected_fields = { + 'fn': 'qwerty', + 'ln': 'azerty', + 'num': '1111', + 'firstname': 'qwerty', + 'lastname': 'azerty', + 'number': '1111', + 'reverse': 'qwerty azerty', + } + self.alice_result = { + 'display': 'Alice Alan', + 'exten': '1111', + 'source': 'third_csv', + 'fields': self.alice_expected_fields, + } + self.qwerty_result_1 = { + 'display': 'qwerty azerty', + 'exten': '1111', + 'source': 'my_csv', + 'fields': self.qwerty_expected_fields, + } + self.qwerty_result_2 = { + 'display': 'qwerty azerty', + 'exten': '1111', + 'source': 'second_csv', + 'fields': self.qwerty_expected_fields, + } def test_reverse_when_no_result(self): result = self.reverse('1234', 'default', VALID_UUID) @@ -129,78 +144,102 @@ def test_reverse_when_no_result(self): assert_that(result, equal_to(expected)) def test_reverse_with_xivo_user_uuid(self): - result = self.get_reverse_result('1111', 'default', VALID_UUID, VALID_TOKEN_MAIN_TENANT) + result = self.get_reverse_result( + '1111', 'default', VALID_UUID, VALID_TOKEN_MAIN_TENANT + ) assert_that(result.status_code, equal_to(200)) def test_reverse_when_multi_result(self): result = self.reverse('1111', 'default', VALID_UUID) - assert_that(result, any_of(self.alice_result, self.qwerty_result_1, self.qwerty_result_2)) + assert_that( + result, + any_of(self.alice_result, self.qwerty_result_1, self.qwerty_result_2), + ) def test_reverse_when_multi_columns(self): result = self.reverse('11112', 'default', VALID_UUID) - expected = {'display': 'Alice Alan', - 'exten': '11112', # <-- matches the mobile - 'source': 'third_csv', - 'fields': self.alice_expected_fields} + expected = { + 'display': 'Alice Alan', + 'exten': '11112', # <-- matches the mobile + 'source': 'third_csv', + 'fields': self.alice_expected_fields, + } assert_that(result, equal_to(expected)) class TestLookupWhenASourceFails(HalfBrokenTestCase): - def test_that_lookup_returns_some_results(self): result = self.lookup('al', 'default') assert_that(result['results'], has_length(2)) - assert_that(result['results'][0]['column_values'], - contains('Alice', 'AAA', '5555555555')) - assert_that(result['results'][1]['column_values'], - contains('Alice', 'AAA', '5555555555')) + assert_that( + result['results'][0]['column_values'], + contains('Alice', 'AAA', '5555555555'), + ) + assert_that( + result['results'][1]['column_values'], + contains('Alice', 'AAA', '5555555555'), + ) class TestDisplay(CSVWithMultipleDisplayTestCase): - def test_that_the_display_is_really_applied_to_lookup(self): result = self.lookup('lice', 'default') - assert_that(result['column_headers'], contains('Firstname', 'Lastname', 'Number', None)) + assert_that( + result['column_headers'], contains('Firstname', 'Lastname', 'Number', None) + ) assert_that(result['column_types'], contains(None, None, None, 'favorite')) def test_display_with_a_type_only(self): result = self.lookup('lice', 'test') - assert_that(result['column_headers'], contains('fn', 'ln', 'Empty', None, 'Default')) - assert_that(result['column_types'], contains('firstname', None, None, 'status', None)) - assert_that(result['results'][0]['column_values'], - contains('Alice', 'AAA', None, None, 'Default')) + assert_that( + result['column_headers'], contains('fn', 'ln', 'Empty', None, 'Default') + ) + assert_that( + result['column_types'], contains('firstname', None, None, 'status', None) + ) + assert_that( + result['results'][0]['column_values'], + contains('Alice', 'AAA', None, None, 'Default'), + ) def test_that_the_display_is_applied_to_headers(self): result = self.headers('default') - assert_that(result['column_headers'], contains('Firstname', 'Lastname', 'Number', None)) + assert_that( + result['column_headers'], contains('Firstname', 'Lastname', 'Number', None) + ) assert_that(result['column_types'], contains(None, None, None, 'favorite')) def test_display_on_headers_with_no_title(self): result = self.headers('test') - assert_that(result['column_headers'], - contains('fn', 'ln', 'Empty', None, 'Default')) - assert_that(result['column_types'], - contains('firstname', None, None, 'status', None)) + assert_that( + result['column_headers'], contains('fn', 'ln', 'Empty', None, 'Default') + ) + assert_that( + result['column_types'], contains('firstname', None, None, 'status', None) + ) class Test404WhenUnknownProfile(CSVWithMultipleDisplayTestCase): - def test_that_lookup_returns_404(self): - result = self.get_lookup_result('lice', 'unknown', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_lookup_result( + 'lice', 'unknown', token=VALID_TOKEN_MAIN_TENANT + ) error = result.json() assert_that(result.status_code, equal_to(404)) - assert_that(error['reason'], contains(all_of(contains_string('profile'), - contains_string('unknown')))) + assert_that( + error['reason'], + contains(all_of(contains_string('profile'), contains_string('unknown'))), + ) def test_that_headers_returns_404(self): result = self.get_headers_result('unknown', token=VALID_TOKEN_MAIN_TENANT) @@ -208,8 +247,10 @@ def test_that_headers_returns_404(self): error = result.json() assert_that(result.status_code, equal_to(404)) - assert_that(error['reason'], contains(all_of(contains_string('profile'), - contains_string('unknown')))) + assert_that( + error['reason'], + contains(all_of(contains_string('profile'), contains_string('unknown'))), + ) def test_that_favorites_returns_404(self): result = self.get_favorites_result('unknown', token=VALID_TOKEN_MAIN_TENANT) @@ -217,14 +258,20 @@ def test_that_favorites_returns_404(self): error = result.json() assert_that(result.status_code, equal_to(404)) - assert_that(error['reason'], contains(all_of(contains_string('profile'), - contains_string('unknown')))) + assert_that( + error['reason'], + contains(all_of(contains_string('profile'), contains_string('unknown'))), + ) def test_that_personal_returns_404(self): - result = self.get_personal_with_profile_result('unknown', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_personal_with_profile_result( + 'unknown', token=VALID_TOKEN_MAIN_TENANT + ) error = result.json() assert_that(result.status_code, equal_to(404)) - assert_that(error['reason'], contains(all_of(contains_string('profile'), - contains_string('unknown')))) + assert_that( + error['reason'], + contains(all_of(contains_string('profile'), contains_string('unknown'))), + ) diff --git a/integration_tests/suite/test_csv_backend.py b/integration_tests/suite/test_csv_backend.py index 46e270d7..82cb8ec0 100644 --- a/integration_tests/suite/test_csv_backend.py +++ b/integration_tests/suite/test_csv_backend.py @@ -4,38 +4,27 @@ import unittest import yaml -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - has_entries, -) - -from .helpers.base import ( - BaseDirdIntegrationTest, - CSVWithMultipleDisplayTestCase, -) +from hamcrest import assert_that, contains, contains_inanyorder, has_entries + +from .helpers.base import BaseDirdIntegrationTest, CSVWithMultipleDisplayTestCase from .helpers.config import new_csv_with_pipes_config from .helpers.constants import VALID_UUID -from .base_dird_integration_test import ( - absolute_file_name, - BackendWrapper, -) +from .base_dird_integration_test import absolute_file_name, BackendWrapper class _BaseCSVFileTestCase(unittest.TestCase): - def setUp(self): config_file = absolute_file_name(self.asset, self.source_config) with open(config_file) as f: config = {'config': yaml.safe_load(f)} - config['config']['file'] = absolute_file_name(self.asset, config['config']['file'][1:]) + config['config']['file'] = absolute_file_name( + self.asset, config['config']['file'][1:] + ) self.backend = BackendWrapper('csv', config) super().setUp() class TestCSVBackend(CSVWithMultipleDisplayTestCase): - def setUp(self): super().setUp() self._alice = ['Alice', 'AAA', '5555555555'] @@ -45,9 +34,10 @@ def test_that_searching_for_lice_return_Alice(self): response = self.lookup('lice', 'default') favorite = [False] - assert_that(response['results'], contains( - has_entries(column_values=self._alice + favorite), - )) + assert_that( + response['results'], + contains(has_entries(column_values=self._alice + favorite)), + ) def test_reverse_lookup(self): response = self.reverse('5555555555', 'default', VALID_UUID) @@ -68,10 +58,13 @@ def test_that_listing_by_ids_works(self): response = self.favorites('default') favorite = [True] - assert_that(response['results'], contains( - has_entries(column_values=self._alice + favorite), - has_entries(column_values=self._charles + favorite), - )) + assert_that( + response['results'], + contains( + has_entries(column_values=self._alice + favorite), + has_entries(column_values=self._charles + favorite), + ), + ) finally: self.delete_favorite('my_csv', alice_id) self.delete_favorite('my_csv', charles_id) @@ -121,8 +114,9 @@ class TestCSVSeparator(BaseDirdIntegrationTest): def test_lookup_with_pipe(self): result = self.lookup('al', 'default') - assert_that(result['results'], contains_inanyorder( - has_entries( - column_values=contains('Alice', 'AAA', '5555555555'), + assert_that( + result['results'], + contains_inanyorder( + has_entries(column_values=contains('Alice', 'AAA', '5555555555')) ), - )) + ) diff --git a/integration_tests/suite/test_csv_http.py b/integration_tests/suite/test_csv_http.py index 8abb570a..a39622eb 100644 --- a/integration_tests/suite/test_csv_http.py +++ b/integration_tests/suite/test_csv_http.py @@ -58,7 +58,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) def get_client(self, token=VALID_TOKEN_MAIN_TENANT): @@ -74,7 +74,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BaseCSVCRUDTestCase): - @fixtures.csv_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -84,7 +83,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.csv_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -114,46 +115,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BaseCSVCRUDTestCase): - @fixtures.csv_source(name='abc') @fixtures.csv_source(name='bcd') @fixtures.csv_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.csv_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.csv_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.csv_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.csv_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.csv_source(name='abc') @@ -162,38 +145,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.csv_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.csv_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.csv_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.csv_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.csv_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -205,43 +172,26 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.csv_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.csv_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.csv_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.csv_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BaseCSVCRUDTestCase): - def test_post(self): try: self.client.csv_source.create({}) @@ -261,9 +211,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.csv_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -273,17 +223,21 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.csv_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.csv_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): @@ -294,7 +248,6 @@ def test_multi_tenant(self): class TestPut(BaseCSVCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { @@ -303,9 +256,7 @@ def setUp(self): 'separator': '|', 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.csv_source(name='foobar') @@ -313,12 +264,16 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.csv_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( calling(self.client.csv_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -337,7 +292,9 @@ def test_put(self, foobar, other): self.fail('Should have raised') assert_that( - calling(self.client.csv_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.csv_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -353,7 +310,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.csv_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -364,9 +321,11 @@ def test_put_multi_tenant(self, sub, main): assert_that( calling(sub_tenant_client.csv_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -377,13 +336,14 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.csv_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.csv_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) class TestGet(BaseCSVCRUDTestCase): - @fixtures.csv_source(name='foobar') def test_get(self, wazo): response = self.client.csv_source.get(wazo['uuid']) diff --git a/integration_tests/suite/test_csv_ws_backend.py b/integration_tests/suite/test_csv_ws_backend.py index 084bc87d..f39bee2e 100644 --- a/integration_tests/suite/test_csv_ws_backend.py +++ b/integration_tests/suite/test_csv_ws_backend.py @@ -1,14 +1,13 @@ # Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import (assert_that, contains, empty, has_entries) +from hamcrest import assert_that, contains, empty, has_entries from .helpers.base import DirdAssetRunningTestCase from .base_dird_integration_test import BackendWrapper class _BaseCSVWSBackend(DirdAssetRunningTestCase): - def setUp(self): self.backend = BackendWrapper('csv_ws', {'config': self.backend_config()}) @@ -19,29 +18,35 @@ class TestCSVWSBackend(_BaseCSVWSBackend): def setUp(self): super().setUp() - self._andree_anne = {'id': '1', - 'firstname': 'Andrée-Anne', - 'lastname': 'Smith', - 'number': '5551231111'} - self._benoit = {'id': '42', - 'firstname': 'Benoît', - 'lastname': 'Malone', - 'number': '5551232222'} + self._andree_anne = { + 'id': '1', + 'firstname': 'Andrée-Anne', + 'lastname': 'Smith', + 'number': '5551231111', + } + self._benoit = { + 'id': '42', + 'firstname': 'Benoît', + 'lastname': 'Malone', + 'number': '5551232222', + } def backend_config(self): return { 'type': 'csv_ws', 'name': 'my_csv', - 'list_url': 'https://localhost:{port}/ws'.format(port=self.service_port(9485, 'ws')), - 'lookup_url': 'https://localhost:{port}/ws'.format(port=self.service_port(9485, 'ws')), + 'list_url': 'https://localhost:{port}/ws'.format( + port=self.service_port(9485, 'ws') + ), + 'lookup_url': 'https://localhost:{port}/ws'.format( + port=self.service_port(9485, 'ws') + ), 'verify_certificate': False, 'delimiter': "|", 'unique_column': 'id', 'searched_columns': ['firstname', 'lastname'], 'first_matched_columns': ['number'], - 'format_columns': { - 'reverse': '{firstname} {lastname}' - }, + 'format_columns': {'reverse': '{firstname} {lastname}'}, } def test_that_verify_certificate_false(self): @@ -78,21 +83,29 @@ class TestCSVWSBackendComa(_BaseCSVWSBackend): def setUp(self): super().setUp() - self._andree_anne = {'id': '1', - 'firstname': 'Andrée-Anne', - 'lastname': 'Smith', - 'number': '5551231111'} - self._benoit = {'id': '42', - 'firstname': 'Benoît', - 'lastname': 'Malone', - 'number': '5551232222'} + self._andree_anne = { + 'id': '1', + 'firstname': 'Andrée-Anne', + 'lastname': 'Smith', + 'number': '5551231111', + } + self._benoit = { + 'id': '42', + 'firstname': 'Benoît', + 'lastname': 'Malone', + 'number': '5551232222', + } def backend_config(self): return { 'type': 'csv_ws', 'name': 'my_csv', - 'list_url': 'http://localhost:{port}/ws'.format(port=self.service_port(9485, 'ws')), - 'lookup_url': 'http://localhost:{port}/ws'.format(port=self.service_port(9485, 'ws')), + 'list_url': 'http://localhost:{port}/ws'.format( + port=self.service_port(9485, 'ws') + ), + 'lookup_url': 'http://localhost:{port}/ws'.format( + port=self.service_port(9485, 'ws') + ), 'delimiter': ',', 'unique_column': 'id', 'searched_columns': ['firstname', 'lastname'], diff --git a/integration_tests/suite/test_csv_ws_http.py b/integration_tests/suite/test_csv_ws_http.py index 78915a3a..ec3ea7bc 100644 --- a/integration_tests/suite/test_csv_ws_http.py +++ b/integration_tests/suite/test_csv_ws_http.py @@ -50,7 +50,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) def get_client(self, token=VALID_TOKEN_MAIN_TENANT): @@ -66,7 +66,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BaseCSVWSCRUDTestCase): - @fixtures.csv_ws_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -76,7 +75,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.csv_ws_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -106,46 +107,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BaseCSVWSCRUDTestCase): - @fixtures.csv_ws_source(name='abc') @fixtures.csv_ws_source(name='bcd') @fixtures.csv_ws_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.csv_ws_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.csv_ws_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.csv_ws_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.csv_ws_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.csv_ws_source(name='abc') @@ -154,38 +137,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.csv_ws_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.csv_ws_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.csv_ws_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.csv_ws_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.csv_ws_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -197,43 +164,26 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.csv_ws_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.csv_ws_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.csv_ws_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.csv_ws_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BaseCSVWSCRUDTestCase): - def test_post(self): try: self.client.csv_ws_source.create({}) @@ -253,9 +203,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.csv_ws_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -265,28 +215,33 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.csv_ws_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.csv_ws_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.csv_ws_source.create).with_args(self.valid_body), + calling(sub_tenant_client.csv_ws_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BaseCSVWSCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { @@ -294,9 +249,7 @@ def setUp(self): 'lookup_url': 'http://example.com/new_lookup_url', 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.csv_ws_source(name='foobar') @@ -304,12 +257,18 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.csv_ws_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( - calling(self.client.csv_ws_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + calling(self.client.csv_ws_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -328,7 +287,9 @@ def test_put(self, foobar, other): self.fail('Should have raised') assert_that( - calling(self.client.csv_ws_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.csv_ws_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -343,7 +304,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.csv_ws_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -354,9 +315,11 @@ def test_put_multi_tenant(self, sub, main): assert_that( calling(sub_tenant_client.csv_ws_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -367,13 +330,14 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.csv_ws_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.csv_ws_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) class TestGet(BaseCSVWSCRUDTestCase): - @fixtures.csv_ws_source(name='foobar') def test_get(self, wazo): response = self.client.csv_ws_source.get(wazo['uuid']) diff --git a/integration_tests/suite/test_database.py b/integration_tests/suite/test_database.py index 1075f24b..a9c198ab 100644 --- a/integration_tests/suite/test_database.py +++ b/integration_tests/suite/test_database.py @@ -5,10 +5,7 @@ import unittest from collections import defaultdict -from contextlib import ( - closing, - contextmanager, -) +from contextlib import closing, contextmanager from uuid import uuid4 from hamcrest import ( any_of, @@ -26,16 +23,9 @@ ) from mock import ANY -from sqlalchemy import ( - and_, - func, - exc, -) +from sqlalchemy import and_, func, exc -from wazo_dird import ( - database, - exception, -) +from wazo_dird import database, exception from xivo_test_helpers.hamcrest.uuid_ import uuid_ from wazo_dird.database.queries import base @@ -67,9 +57,12 @@ def wrapped(self, *args, **kwargs): session.add(user) session.commit() result = f(self, user_uuid, *args, **kwargs) - session.query(database.User).filter(database.User.xivo_user_uuid == user_uuid).delete() + session.query(database.User).filter( + database.User.xivo_user_uuid == user_uuid + ).delete() session.commit() return result + return wrapped @@ -91,7 +84,6 @@ def teardown_module(): class _BaseTest(unittest.TestCase): - def setUp(self): self.display_crud = database.DisplayCRUD(Session) self.profile_crud = database.ProfileCRUD(Session) @@ -136,9 +128,7 @@ def _insert_personal_contacts(self, xivo_user_uuid, *contacts): ids.append(dird_contact.uuid) for name, value in contact.items(): field = database.ContactFields( - name=name, - value=value, - contact_uuid=dird_contact.uuid, + name=name, value=value, contact_uuid=dird_contact.uuid ) session.add(field) session.commit() @@ -153,7 +143,6 @@ def _list_contacts(self): class _BasePhonebookCRUDTest(_BaseTest): - def setUp(self): super().setUp() self._crud = database.PhonebookCRUD(Session) @@ -171,7 +160,6 @@ def _new_phonebook(self, tenant_uuid, name, description=None, delete=True): class TestBaseDAO(_BaseTest): - def test_that_an_unexpected_error_does_not_block_the_current_Session(self): dao = base.BaseDAO(Session) @@ -194,7 +182,6 @@ def test_that_an_unexpected_error_does_not_block_the_current_Session(self): class TestDisplayCRUD(_BaseTest): - def test_create_no_error(self): tenant_uuid = new_uuid() name = 'english' @@ -202,20 +189,9 @@ def test_create_no_error(self): 'tenant_uuid': tenant_uuid, 'name': name, 'columns': [ - { - 'field': 'firstname', - 'title': 'Firstname', - }, - { - 'field': 'lastname', - 'title': 'Lastname', - 'default': '', - }, - { - 'field': 'number', - 'title': 'Number', - 'type': 'number', - }, + {'field': 'firstname', 'title': 'Firstname'}, + {'field': 'lastname', 'title': 'Lastname', 'default': ''}, + {'field': 'number', 'title': 'Number', 'type': 'number'}, { 'field': 'mobile', 'title': 'Mobile', @@ -227,33 +203,25 @@ def test_create_no_error(self): result = self.display_crud.create(**body) try: - assert_that(result, has_entries( - uuid=uuid_(), - tenant_uuid=tenant_uuid, - name=name, - columns=contains( - has_entries( - field='firstname', - title='Firstname', - ), - has_entries( - field='lastname', - title='Lastname', - default='', - ), - has_entries( - field='number', - title='Number', - type='number', - ), - has_entries( - field='mobile', - title='Mobile', - type='number', - number_display='{firstname} {lastname} (Mobile)', + assert_that( + result, + has_entries( + uuid=uuid_(), + tenant_uuid=tenant_uuid, + name=name, + columns=contains( + has_entries(field='firstname', title='Firstname'), + has_entries(field='lastname', title='Lastname', default=''), + has_entries(field='number', title='Number', type='number'), + has_entries( + field='mobile', + title='Mobile', + type='number', + number_display='{firstname} {lastname} (Mobile)', + ), ), ), - )) + ) finally: self.display_crud.delete(None, result['uuid']) @@ -263,7 +231,9 @@ def test_get_with_the_right_tenant(self, display): assert_that(result, equal_to(display)) assert_that( - calling(self.display_crud.get).with_args([display['tenant_uuid']], new_uuid()), + calling(self.display_crud.get).with_args( + [display['tenant_uuid']], new_uuid() + ), raises(exception.NoSuchDisplay), ) @@ -287,11 +257,15 @@ def test_get_with_no_tenant(self, display): @fixtures.display() def test_delete_with_the_right_tenant(self, display): assert_that( - calling(self.display_crud.delete).with_args([display['tenant_uuid']], display['uuid']), + calling(self.display_crud.delete).with_args( + [display['tenant_uuid']], display['uuid'] + ), not_(raises(Exception)), ) assert_that( - calling(self.display_crud.delete).with_args([display['tenant_uuid']], display['uuid']), + calling(self.display_crud.delete).with_args( + [display['tenant_uuid']], display['uuid'] + ), raises(exception.NoSuchDisplay), ) @@ -316,12 +290,11 @@ def test_delete_with_no_tenant(self, display): class TestPhonebookCRUDCount(_BasePhonebookCRUDTest): - def test_count(self): tenant_uuid = new_uuid() - with self._new_phonebook(tenant_uuid, 'a'), \ - self._new_phonebook(tenant_uuid, 'b'), \ - self._new_phonebook(tenant_uuid, 'c'): + with self._new_phonebook(tenant_uuid, 'a'), self._new_phonebook( + tenant_uuid, 'b' + ), self._new_phonebook(tenant_uuid, 'c'): result = self._crud.count(tenant_uuid) assert_that(result, equal_to(3)) @@ -333,25 +306,24 @@ def test_that_an_unknown_tenant_returns_zero(self): def test_that_phonebooks_from_others_are_not_counted(self): tenant = 't' - with self._new_phonebook(tenant, 'a'), \ - self._new_phonebook(tenant, 'b'), \ - self._new_phonebook('other', 'c'): + with self._new_phonebook(tenant, 'a'), self._new_phonebook( + tenant, 'b' + ), self._new_phonebook('other', 'c'): result = self._crud.count(tenant) assert_that(result, equal_to(2)) def test_that_only_matching_phonebooks_are_counted(self): tenant = 't' - with self._new_phonebook(tenant, 'ab'), \ - self._new_phonebook(tenant, 'bc'), \ - self._new_phonebook(tenant, 'cd'): + with self._new_phonebook(tenant, 'ab'), self._new_phonebook( + tenant, 'bc' + ), self._new_phonebook(tenant, 'cd'): result = self._crud.count(tenant, search='b') assert_that(result, equal_to(2)) class TestPhonebookCRUDCreate(_BasePhonebookCRUDTest): - def tearDown(self): with closing(Session()) as session: for phonebook in session.query(database.Phonebook).all(): @@ -361,10 +333,7 @@ def tearDown(self): def test_that_create_creates_a_phonebook_and_a_tenant(self): tenant = 'default' - body = { - 'name': 'main', - 'description': 'The main phonebook for "default"', - } + body = {'name': 'main', 'description': 'The main phonebook for "default"'} result = self._crud.create(tenant, body) @@ -374,13 +343,9 @@ def test_that_create_without_name_fails(self): tenant = 'default' assert_that( - calling(self._crud.create).with_args(tenant, None), - raises(Exception), - ) - assert_that( - calling(self._crud.create).with_args(tenant, {}), - raises(Exception), + calling(self._crud.create).with_args(tenant, None), raises(Exception) ) + assert_that(calling(self._crud.create).with_args(tenant, {}), raises(Exception)) assert_that( calling(self._crud.create).with_args(tenant, {'name': ''}), raises(Exception), @@ -399,8 +364,7 @@ def test_that_create_with_invalid_fields_raises(self): body = {'name': 'nodesc', 'foo': 'bar'} assert_that( - calling(self._crud.create).with_args(tenant, body), - raises(TypeError), + calling(self._crud.create).with_args(tenant, body), raises(TypeError) ) def test_that_create_raises_if_two_phonebook_have_the_same_name_and_tenant(self): @@ -420,15 +384,16 @@ def test_that_duplicate_tenants_are_not_created(self): self._crud.create(tenant_uuid, {'name': 'second'}) with closing(Session()) as session: - tenant_count = session.query(func.count(database.Tenant.uuid)).filter( - database.Tenant.uuid == tenant_uuid, - ).scalar() + tenant_count = ( + session.query(func.count(database.Tenant.uuid)) + .filter(database.Tenant.uuid == tenant_uuid) + .scalar() + ) assert_that(tenant_count, equal_to(1)) class TestPhonebookCRUDDelete(_BasePhonebookCRUDTest): - def test_that_delete_removes_the_phonebook(self): tenant = 'default' with self._new_phonebook(tenant, 'first', delete=False) as phonebook: @@ -436,8 +401,7 @@ def test_that_delete_removes_the_phonebook(self): with closing(Session()) as session: phonebook_count = ( - session - .query(func.count(database.Phonebook.id)) + session.query(func.count(database.Phonebook.id)) .filter(database.Phonebook.id == phonebook['id']) .scalar() ) @@ -445,8 +409,10 @@ def test_that_delete_removes_the_phonebook(self): assert_that(phonebook_count, equal_to(0)) def test_that_deleting_an_unknown_phonebook_raises(self): - assert_that(calling(self._crud.delete).with_args('tenant', 42), - raises(exception.NoSuchPhonebook)) + assert_that( + calling(self._crud.delete).with_args('tenant', 42), + raises(exception.NoSuchPhonebook), + ) def test_that_deleting_another_tenant_phonebook_is_not_possible(self): tenant_a = 'a' @@ -469,15 +435,17 @@ def test_that_tenants_are_not_created_on_delete(self): pass # as expected with closing(Session()) as session: - tenant_created = session.query( - func.count(database.Tenant.uuid), - ).filter(database.Tenant.name == tenant_b).scalar() > 0 + tenant_created = ( + session.query(func.count(database.Tenant.uuid)) + .filter(database.Tenant.name == tenant_b) + .scalar() + > 0 + ) assert_that(tenant_created, equal_to(False)) class TestPhonebookCRUDEdit(_BasePhonebookCRUDTest): - def test_that_edit_changes_the_phonebook(self): tenant = 'tenant' @@ -501,20 +469,24 @@ def test_that_invalid_keys_raise_an_exception(self): def test_that_editing_an_unknown_phonebook_raises(self): tenant = 'tenant' - assert_that(calling(self._crud.edit).with_args(tenant, 42, {'name': 'test'}), - raises(exception.NoSuchPhonebook)) + assert_that( + calling(self._crud.edit).with_args(tenant, 42, {'name': 'test'}), + raises(exception.NoSuchPhonebook), + ) def test_that_editing_a_phonebook_from_another_tenant_raises(self): - with self._new_phonebook('tenant_a', 'a') as phonebook_a, \ - self._new_phonebook('tenant_b', 'b'): + with self._new_phonebook('tenant_a', 'a') as phonebook_a, self._new_phonebook( + 'tenant_b', 'b' + ): assert_that( - calling(self._crud.edit).with_args('tenant_b', phonebook_a['id'], {'name': 'foo'}), + calling(self._crud.edit).with_args( + 'tenant_b', phonebook_a['id'], {'name': 'foo'} + ), raises(exception.NoSuchPhonebook), ) class TestPhonebookCRUDGet(_BasePhonebookCRUDTest): - def test_that_get_returns_the_phonebook(self): with self._new_phonebook('tenant', 'a') as phonebook: result = self._crud.get('tenant', phonebook['id']) @@ -536,20 +508,19 @@ def test_that_get_from_another_tenant_raises(self): class TestPhonebookCRUDList(_BasePhonebookCRUDTest): - def test_that_all_phonebooks_are_listed(self): tenant = 't' - with self._new_phonebook(tenant, 'a') as a, \ - self._new_phonebook(tenant, 'b') as b, \ - self._new_phonebook(tenant, 'c') as c: + with self._new_phonebook(tenant, 'a') as a, self._new_phonebook( + tenant, 'b' + ) as b, self._new_phonebook(tenant, 'c') as c: result = self._crud.list(tenant) assert_that(result, contains_inanyorder(a, b, c)) def test_that_phonebooks_from_others_are_not_listed(self): tenant = 't' - with self._new_phonebook(tenant, 'a') as a, \ - self._new_phonebook(tenant, 'b') as b, \ - self._new_phonebook('not_t', 'c'): + with self._new_phonebook(tenant, 'a') as a, self._new_phonebook( + tenant, 'b' + ) as b, self._new_phonebook('not_t', 'c'): result = self._crud.list(tenant) assert_that(result, contains_inanyorder(a, b)) @@ -560,17 +531,21 @@ def test_that_no_phonebooks_returns_an_empty_list(self): def test_that_phonebooks_can_be_ordered(self): tenant = 't' - with self._new_phonebook(tenant, 'a', description='z') as a, \ - self._new_phonebook(tenant, 'b', description='b') as b, \ - self._new_phonebook(tenant, 'c') as c: + with self._new_phonebook( + tenant, 'a', description='z' + ) as a, self._new_phonebook( + tenant, 'b', description='b' + ) as b, self._new_phonebook( + tenant, 'c' + ) as c: result = self._crud.list(tenant, order='description') assert_that(result, contains_inanyorder(b, a, c)) def test_that_phonebooks_order_with_invalid_field_raises(self): tenant = 't' - with self._new_phonebook(tenant, 'a', description='z'), \ - self._new_phonebook(tenant, 'b', description='b'), \ - self._new_phonebook(tenant, 'c'): + with self._new_phonebook(tenant, 'a', description='z'), self._new_phonebook( + tenant, 'b', description='b' + ), self._new_phonebook(tenant, 'c'): assert_that( calling(self._crud.list).with_args(tenant, order='foo'), raises(TypeError), @@ -578,40 +553,45 @@ def test_that_phonebooks_order_with_invalid_field_raises(self): def test_that_phonebooks_can_be_ordered_in_any_order(self): tenant = 't' - with self._new_phonebook(tenant, 'a', description='z') as a, \ - self._new_phonebook(tenant, 'b', description='b') as b, \ - self._new_phonebook(tenant, 'c') as c: + with self._new_phonebook( + tenant, 'a', description='z' + ) as a, self._new_phonebook( + tenant, 'b', description='b' + ) as b, self._new_phonebook( + tenant, 'c' + ) as c: result = self._crud.list(tenant, order='description', direction='desc') assert_that(result, contains_inanyorder(a, b, c)) def test_that_phonebooks_can_be_limited(self): tenant = 't' - with self._new_phonebook(tenant, 'a') as a, \ - self._new_phonebook(tenant, 'b') as b, \ - self._new_phonebook(tenant, 'c'): + with self._new_phonebook(tenant, 'a') as a, self._new_phonebook( + tenant, 'b' + ) as b, self._new_phonebook(tenant, 'c'): result = self._crud.list(tenant, limit=2) assert_that(result, contains_inanyorder(a, b)) def test_that_an_offset_can_be_supplied(self): tenant = 't' - with self._new_phonebook(tenant, 'a'), \ - self._new_phonebook(tenant, 'b'), \ - self._new_phonebook(tenant, 'c') as c: + with self._new_phonebook(tenant, 'a'), self._new_phonebook( + tenant, 'b' + ), self._new_phonebook(tenant, 'c') as c: result = self._crud.list(tenant, offset=2) assert_that(result, contains_inanyorder(c)) def test_that_list_only_returns_matching_phonebooks(self): tenant = 't' - with self._new_phonebook(tenant, 'aa', description='foobar') as a, \ - self._new_phonebook(tenant, 'bb') as b, \ - self._new_phonebook(tenant, 'cc'): + with self._new_phonebook( + tenant, 'aa', description='foobar' + ) as a, self._new_phonebook(tenant, 'bb') as b, self._new_phonebook( + tenant, 'cc' + ): result = self._crud.list(tenant, search='b') assert_that(result, contains_inanyorder(a, b)) class _BasePhonebookContactCRUDTest(_BaseTest): - def setUp(self): super().setUp() self._tenant = 'the-tenant' @@ -620,11 +600,7 @@ def setUp(self): body = {'name': 'main', 'description': 'the integration test phonebook'} self._phonebook = self._phonebook_crud.create(self._tenant, body) self._phonebook_id = self._phonebook['id'] - self._body = { - 'firstname': 'Foo', - 'lastname': 'bar', - 'number': '5555555555', - } + self._body = {'firstname': 'Foo', 'lastname': 'bar', 'number': '5555555555'} def tearDown(self): self._phonebook_crud.delete(self._tenant, self._phonebook_id) @@ -632,7 +608,6 @@ def tearDown(self): class TestPhonebookContactCRUDCreate(_BasePhonebookContactCRUDTest): - def test_that_a_phonebook_contact_can_be_created(self): result = self._crud.create(self._tenant, self._phonebook_id, self._body) @@ -644,7 +619,9 @@ def test_that_a_phonebook_contact_can_be_created(self): def test_that_duplicated_contacts_cannot_be_created(self): self._crud.create(self._tenant, self._phonebook_id, self._body) assert_that( - calling(self._crud.create).with_args(self._tenant, self._phonebook_id, self._body), + calling(self._crud.create).with_args( + self._tenant, self._phonebook_id, self._body + ), raises(exception.DuplicatedContactException), ) @@ -658,13 +635,14 @@ def test_that_duplicates_can_happen_in_different_phonebooks(self): def test_that_a_tenant_can_only_create_in_his_phonebook(self): assert_that( - calling(self._crud.create).with_args('not-the-tenant', self._phonebook_id, self._body), + calling(self._crud.create).with_args( + 'not-the-tenant', self._phonebook_id, self._body + ), raises(exception.NoSuchPhonebook), ) class TestPhonebookContactImport(_BasePhonebookContactCRUDTest): - def test_that_I_can_create_many_contacts(self): contact_1 = self._new_contact('Foo', 'Bar', '5555551111') contact_2 = self._new_contact('Alice', 'AAA', '5555552222') @@ -673,11 +651,14 @@ def test_that_I_can_create_many_contacts(self): created, errors = self._crud.create_many(self._tenant, self._phonebook_id, body) - assert_that(created, contains_inanyorder( - has_entries(**contact_1), - has_entries(**contact_2), - has_entries(**contact_3), - )) + assert_that( + created, + contains_inanyorder( + has_entries(**contact_1), + has_entries(**contact_2), + has_entries(**contact_3), + ), + ) assert_that(errors, empty()) def test_that_an_error_does_not_break_the_whole_import(self): @@ -688,23 +669,18 @@ def test_that_an_error_does_not_break_the_whole_import(self): created, errors = self._crud.create_many(self._tenant, self._phonebook_id, body) - assert_that(created, contains_inanyorder( - has_entries(**contact_1), - has_entries(**contact_3), - )) + assert_that( + created, + contains_inanyorder(has_entries(**contact_1), has_entries(**contact_3)), + ) assert_that(errors, contains_inanyorder(has_entries(**contact_2))) @staticmethod def _new_contact(firstname, lastname, number): - return { - 'firstname': firstname, - 'lastname': lastname, - 'number': number, - } + return {'firstname': firstname, 'lastname': lastname, 'number': number} class TestPhonebookContactCRUDDelete(_BasePhonebookContactCRUDTest): - def test_that_deleting_contact_removes_it(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) @@ -717,7 +693,7 @@ def test_that_deleting_with_another_tenant_does_not_work(self): assert_that( calling(self._crud.delete).with_args( - 'not-the-tenant', self._phonebook_id, contact['id'], + 'not-the-tenant', self._phonebook_id, contact['id'] ), raises(exception.NoSuchPhonebook), ) @@ -728,14 +704,13 @@ def test_that_deleting_an_unknown_contact_raises(self): assert_that( calling(self._crud.delete).with_args( - self._tenant, self._phonebook_id, unknown_contact_uuid, + self._tenant, self._phonebook_id, unknown_contact_uuid ), raises(exception.NoSuchContact), ) class TestPhonebookContactCRUDGet(_BasePhonebookContactCRUDTest): - def test_that_get_returns_the_contact(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) @@ -748,7 +723,9 @@ def test_that_get_wont_work_with_the_wrong_phonebook_id(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) assert_that( - calling(self._crud.get).with_args(self._tenant, other_phonebook['id'], contact['id']), + calling(self._crud.get).with_args( + self._tenant, other_phonebook['id'], contact['id'] + ), raises(exception.NoSuchContact), ) @@ -756,23 +733,22 @@ def test_that_get_wont_work_with_the_wrong_tenant(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) assert_that( - calling(self._crud.get).with_args('not-the-tenant', self._phonebook_id, contact['id']), + calling(self._crud.get).with_args( + 'not-the-tenant', self._phonebook_id, contact['id'] + ), raises(exception.NoSuchPhonebook), ) class TestPhonebookContactCRUDEdit(_BasePhonebookContactCRUDTest): - def test_that_editing_a_contact_works(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) - new_body = { - 'firstname': 'Foo', - 'lastname': 'Bar', - 'number': '5551236666', - } + new_body = {'firstname': 'Foo', 'lastname': 'Bar', 'number': '5551236666'} - result = self._crud.edit(self._tenant, self._phonebook_id, contact['id'], new_body) + result = self._crud.edit( + self._tenant, self._phonebook_id, contact['id'], new_body + ) expected = dict(new_body) expected['id'] = ANY @@ -785,11 +761,13 @@ def test_that_the_id_cannot_be_modified(self): new_body = dict(contact) new_body['id'] = new_uuid() - result = self._crud.edit(self._tenant, self._phonebook_id, contact['id'], new_body) + result = self._crud.edit( + self._tenant, self._phonebook_id, contact['id'], new_body + ) assert_that(result, equal_to(contact)) assert_that(self._list_contacts(), has_item(contact)) - assert_that(self._list_contacts(), not(has_item(new_body))) + assert_that(self._list_contacts(), not (has_item(new_body))) def test_that_duplicates_cannot_be_created(self): self._crud.create(self._tenant, self._phonebook_id, {'name': 'Foo'}) @@ -806,19 +784,17 @@ def test_that_duplicates_cannot_be_created(self): ) def test_that_the_phonebook_must_match_the_id(self): - other_phonebook = self._phonebook_crud.create(self._tenant, {'name': 'the other'}) + other_phonebook = self._phonebook_crud.create( + self._tenant, {'name': 'the other'} + ) contact = self._crud.create(self._tenant, self._phonebook_id, self._body) - new_body = { - 'firstname': 'Foo', - 'lastname': 'Bar', - 'number': '5551236666', - } + new_body = {'firstname': 'Foo', 'lastname': 'Bar', 'number': '5551236666'} other_phonebook_id = other_phonebook['id'] assert_that( calling(self._crud.edit).with_args( - self._tenant, other_phonebook_id, contact['id'], new_body, + self._tenant, other_phonebook_id, contact['id'], new_body ), raises(exception.NoSuchContact), ) @@ -826,38 +802,36 @@ def test_that_the_phonebook_must_match_the_id(self): def test_that_the_tenant_must_match_the_id(self): contact = self._crud.create(self._tenant, self._phonebook_id, self._body) - new_body = { - 'firstname': 'Foo', - 'lastname': 'Bar', - 'number': '5551236666', - } + new_body = {'firstname': 'Foo', 'lastname': 'Bar', 'number': '5551236666'} assert_that( calling(self._crud.edit).with_args( - 'not-the-tenant', self._phonebook_id, contact['id'], new_body, + 'not-the-tenant', self._phonebook_id, contact['id'], new_body ), raises(exception.NoSuchPhonebook), ) class TestPhonebookContactCRUDList(_BasePhonebookContactCRUDTest): - def setUp(self): super().setUp() self._contact_1 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'one', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'one', 'foo': 'bar'} ) self._contact_2 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'two', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'two', 'foo': 'bar'} ) self._contact_3 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'three', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'three', 'foo': 'bar'} ) def test_that_listing_contacts_works(self): result = self._crud.list(self._tenant, self._phonebook_id) - assert_that(result, contains_inanyorder(self._contact_1, self._contact_2, self._contact_3)) + assert_that( + result, + contains_inanyorder(self._contact_1, self._contact_2, self._contact_3), + ) def test_that_only_the_tenant_can_list(self): assert_that( @@ -872,17 +846,16 @@ def test_that_the_list_can_be_filtered(self): class TestPhonebookContactCRUDCount(_BasePhonebookContactCRUDTest): - def setUp(self): super().setUp() self._contact_1 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'one', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'one', 'foo': 'bar'} ) self._contact_2 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'two', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'two', 'foo': 'bar'} ) self._contact_3 = self._crud.create( - self._tenant, self._phonebook_id, {'name': 'three', 'foo': 'bar'}, + self._tenant, self._phonebook_id, {'name': 'three', 'foo': 'bar'} ) def test_that_counting_counts(self): @@ -903,7 +876,6 @@ def test_that_counting_from_another_tenant_return_0(self): class TestContactCRUD(_BaseTest): - def setUp(self): super().setUp() self._crud = database.PersonalContactCRUD(Session) @@ -918,7 +890,9 @@ def test_that_create_personal_contact_creates_a_contact_and_the_owner(self): assert_that(contact_list, contains(expected(self.contact_1))) @with_user_uuid - def test_that_create_personal_contact_creates_with_existing_owner(self, xivo_user_uuid): + def test_that_create_personal_contact_creates_with_existing_owner( + self, xivo_user_uuid + ): result = self._crud.create_personal_contact(xivo_user_uuid, self.contact_1) assert_that(result, equal_to(expected(self.contact_1))) @@ -929,42 +903,49 @@ def test_that_create_personal_contact_creates_with_existing_owner(self, xivo_use def test_that_personal_contacts_are_unique(self, xivo_user_uuid): self._crud.create_personal_contact(xivo_user_uuid, self.contact_1) assert_that( - calling(self._crud.create_personal_contact).with_args(xivo_user_uuid, self.contact_1), + calling(self._crud.create_personal_contact).with_args( + xivo_user_uuid, self.contact_1 + ), raises(exception.DuplicatedContactException), ) @with_user_uuid def test_that_personal_contacts_remain_unique(self, xivo_user_uuid): - contact_1_uuid = self._crud.create_personal_contact(xivo_user_uuid, self.contact_1)['id'] + contact_1_uuid = self._crud.create_personal_contact( + xivo_user_uuid, self.contact_1 + )['id'] self._crud.create_personal_contact(xivo_user_uuid, self.contact_2)['id'] assert_that( calling(self._crud.edit_personal_contact).with_args( - xivo_user_uuid, contact_1_uuid, self.contact_2, + xivo_user_uuid, contact_1_uuid, self.contact_2 ), raises(exception.DuplicatedContactException), ) contact_list = self._crud.list_personal_contacts(xivo_user_uuid) - assert_that(contact_list, contains_inanyorder( - expected(self.contact_1), expected(self.contact_2), - )) + assert_that( + contact_list, + contains_inanyorder(expected(self.contact_1), expected(self.contact_2)), + ) @with_user_uuid @with_user_uuid def test_that_personal_contacts_can_be_duplicated_between_users( - self, - user_uuid_1, - user_uuid_2, + self, user_uuid_1, user_uuid_2 ): - contact_1_uuid = self._crud.create_personal_contact(user_uuid_1, self.contact_1)['id'] - contact_2_uuid = self._crud.create_personal_contact(user_uuid_2, self.contact_1)['id'] + contact_1_uuid = self._crud.create_personal_contact( + user_uuid_1, self.contact_1 + )['id'] + contact_2_uuid = self._crud.create_personal_contact( + user_uuid_2, self.contact_1 + )['id'] assert_that(contact_1_uuid, not_(equal_to(contact_2_uuid))) @with_user_uuid def test_get_personal_contact(self, xivo_user_uuid): contact_uuid, _, __ = self._insert_personal_contacts( - xivo_user_uuid, self.contact_1, self.contact_2, self.contact_3, + xivo_user_uuid, self.contact_1, self.contact_2, self.contact_3 ) result = self._crud.get_personal_contact(xivo_user_uuid, contact_uuid) @@ -975,11 +956,13 @@ def test_get_personal_contact(self, xivo_user_uuid): @with_user_uuid def test_get_personal_contact_from_another_user(self, user_1_uuid, user_2_uuid): contact_uuid, _, __ = self._insert_personal_contacts( - user_1_uuid, self.contact_1, self.contact_2, self.contact_3, + user_1_uuid, self.contact_1, self.contact_2, self.contact_3 ) assert_that( - calling(self._crud.get_personal_contact).with_args(user_2_uuid, contact_uuid), + calling(self._crud.get_personal_contact).with_args( + user_2_uuid, contact_uuid + ), raises(exception.NoSuchContact), ) @@ -990,7 +973,9 @@ def test_delete_personal_contact(self, xivo_user_uuid): self._crud.delete_personal_contact(xivo_user_uuid, contact_uuid) assert_that( - calling(self._crud.get_personal_contact).with_args(xivo_user_uuid, contact_uuid), + calling(self._crud.get_personal_contact).with_args( + xivo_user_uuid, contact_uuid + ), raises(exception.NoSuchContact), ) @@ -1000,36 +985,45 @@ def test_delete_personal_contact_from_another_user(self, user_1_uuid, user_2_uui contact_uuid, = self._insert_personal_contacts(user_1_uuid, self.contact_1) assert_that( - calling(self._crud.delete_personal_contact).with_args(user_2_uuid, contact_uuid), + calling(self._crud.delete_personal_contact).with_args( + user_2_uuid, contact_uuid + ), raises(exception.NoSuchContact), ) @with_user_uuid @with_user_uuid - def test_delete_all_personal_contact_from_another_user(self, user_1_uuid, user_2_uuid): + def test_delete_all_personal_contact_from_another_user( + self, user_1_uuid, user_2_uuid + ): contact_uuid_1, = self._insert_personal_contacts(user_1_uuid, self.contact_1) contact_uuid_2, contact_uuid_3 = self._insert_personal_contacts( - user_2_uuid, self.contact_2, self.contact_3, + user_2_uuid, self.contact_2, self.contact_3 ) self._crud.delete_all_personal_contacts(user_2_uuid) assert_that( - calling(self._crud.get_personal_contact).with_args(user_1_uuid, contact_uuid_1), + calling(self._crud.get_personal_contact).with_args( + user_1_uuid, contact_uuid_1 + ), not_(raises(exception.NoSuchContact)), ) assert_that( - calling(self._crud.get_personal_contact).with_args(user_2_uuid, contact_uuid_2), + calling(self._crud.get_personal_contact).with_args( + user_2_uuid, contact_uuid_2 + ), raises(exception.NoSuchContact), ) assert_that( - calling(self._crud.get_personal_contact).with_args(user_2_uuid, contact_uuid_3), + calling(self._crud.get_personal_contact).with_args( + user_2_uuid, contact_uuid_3 + ), raises(exception.NoSuchContact), ) class TestFavoriteCrud(_BaseTest): - def setUp(self): super().setUp() self._crud = database.FavoriteCRUD(Session) @@ -1055,7 +1049,9 @@ def test_that_creating_the_same_favorite_raises(self, source, user_uuid): source, contact_id, backend = 'source', 'the-contact-id', 'backend' self._crud.create(user_uuid, backend, source, contact_id) assert_that( - calling(self._crud.create).with_args(user_uuid, backend, source, contact_id), + calling(self._crud.create).with_args( + user_uuid, backend, source, contact_id + ), raises(exception.DuplicatedFavoriteException), ) @@ -1076,15 +1072,8 @@ def test_get(self, source_3, source_2, source_1, user_1, user_2): fav_1 = self._crud.get(user_1) fav_2 = self._crud.get(user_2) - assert_that(fav_1, contains_inanyorder( - ('s1', '1'), - ('s2', '1'), - ('s1', '42'), - )) - assert_that(fav_2, contains_inanyorder( - ('s1', '42'), - ('s3', '1'), - )) + assert_that(fav_1, contains_inanyorder(('s1', '1'), ('s2', '1'), ('s1', '42'))) + assert_that(fav_2, contains_inanyorder(('s1', '42'), ('s3', '1'))) @fixtures.source(backend='backend', name='source') @with_user_uuid @@ -1102,7 +1091,9 @@ def test_that_delete_removes_a_favorite(self, xivo_user_uuid, source): @fixtures.source(backend='backend', name='source') @with_user_uuid @with_user_uuid - def test_that_delete_does_not_remove_favorites_from_other_users(self, user_1, user_2, source): + def test_that_delete_does_not_remove_favorites_from_other_users( + self, user_1, user_2, source + ): backend = 'backend' self._crud.create(user_2, backend, 'source', 'the-contact-id') @@ -1117,7 +1108,9 @@ def test_that_delete_does_not_remove_favorites_from_other_users(self, user_1, us @with_user_uuid def test_that_delete_raises_if_not_found(self, xivo_user_uuid, source): assert_that( - calling(self._crud.delete).with_args(xivo_user_uuid, 'source', 'the-contact-id'), + calling(self._crud.delete).with_args( + xivo_user_uuid, 'source', 'the-contact-id' + ), raises(exception.NoSuchFavorite), ) @@ -1128,15 +1121,19 @@ def test_that_delete_from_an_unknown_source_raises(self, xivo_user_uuid, source) self._crud.create(xivo_user_uuid, backend, 'source', 'the-contact-id') assert_that( - calling(self._crud.delete).with_args(xivo_user_uuid, 'not-source', 'the-contact-id'), + calling(self._crud.delete).with_args( + xivo_user_uuid, 'not-source', 'the-contact-id' + ), raises(exception.NoSuchFavorite), ) def _user_exists(self, xivo_user_uuid): with closing(Session()) as session: - user_uuid = session.query(database.User.xivo_user_uuid).filter( - database.User.xivo_user_uuid == xivo_user_uuid - ).scalar() + user_uuid = ( + session.query(database.User.xivo_user_uuid) + .filter(database.User.xivo_user_uuid == xivo_user_uuid) + .scalar() + ) return user_uuid is not None @@ -1146,11 +1143,13 @@ def _favorite_exists(self, xivo_user_uuid, source_name, contact_id): session.query(database.Favorite) .join(database.Source) .join(database.User) - .filter(and_( - database.User.xivo_user_uuid == xivo_user_uuid, - database.Source.name == source_name, - database.Favorite.contact_id == contact_id, - )) + .filter( + and_( + database.User.xivo_user_uuid == xivo_user_uuid, + database.Source.name == source_name, + database.Favorite.contact_id == contact_id, + ) + ) ).first() return favorite is not None @@ -1164,7 +1163,9 @@ def setUp(self): super().setUp() self.phonebook_crud = database.PhonebookCRUD(Session) self.phonebook_contact_crud = database.PhonebookContactCRUD(Session) - self.phonebook_id = self.phonebook_crud.create(self.tenant_uuid, {'name': 'test'})['id'] + self.phonebook_id = self.phonebook_crud.create( + self.tenant_uuid, {'name': 'test'} + )['id'] bodies = [ {'firstname': 'Mia', 'lastname': 'Wallace', 'number': '5551111111'}, {'firstname': 'Marcellus', 'lastname': 'Wallace', 'number': '5551111111'}, @@ -1173,12 +1174,19 @@ def setUp(self): {'firstname': 'Butch', 'lastname': 'Coolidge'}, {'firstname': 'Jimmie', 'lastname': 'Dimmick', 'number': '5554444444'}, ] - [self.mia, self.marcellus, self.vincent, self.jules, self.butch, self.jimmie] = [ + [ + self.mia, + self.marcellus, + self.vincent, + self.jules, + self.butch, + self.jimmie, + ] = [ self.phonebook_contact_crud.create( - self.tenant_uuid, - self.phonebook_id, - body, - ) for body in bodies] + self.tenant_uuid, self.phonebook_id, body + ) + for body in bodies + ] self.engine = database.PhonebookContactSearchEngine( Session, self.tenant_uuid, @@ -1203,10 +1211,7 @@ def test_that_none_matching_search_returns_an_empty_list(self): def test_that_no_searched_columns_does_not_search(self): engine = database.PhonebookContactSearchEngine( - Session, - self.tenant_uuid, - self.phonebook_id, - first_match_columns=['number'], + Session, self.tenant_uuid, self.phonebook_id, first_match_columns=['number'] ) result = engine.find_contacts('a') @@ -1218,46 +1223,59 @@ def test_that_find_first_returns_a_contact(self): assert_that(result, any_of(self.mia, self.marcellus)) def test_that_listing_contacts_works(self): - result = self.engine.list_contacts([self.mia['id'], self.butch['id'], self.jimmie['id']]) + result = self.engine.list_contacts( + [self.mia['id'], self.butch['id'], self.jimmie['id']] + ) assert_that(result, contains_inanyorder(self.mia, self.butch, self.jimmie)) def test_that_listing_is_limited_to_the_current_phonebook_and_tenant(self): shire_phonebook = self.phonebook_crud.create('lotr', {'name': 'shire'}) frodo = self.phonebook_contact_crud.create( - 'lotr', shire_phonebook['id'], {'firstname': 'Frodo', 'lastname': 'Baggins'}, + 'lotr', shire_phonebook['id'], {'firstname': 'Frodo', 'lastname': 'Baggins'} ) - result = self.engine.list_contacts([self.mia['id'], frodo['id'], self.jimmie['id']]) + result = self.engine.list_contacts( + [self.mia['id'], frodo['id'], self.jimmie['id']] + ) assert_that(result, contains_inanyorder(self.mia, self.jimmie)) class TestPersonalContactSearchEngine(_BaseTest): - @with_user_uuid def test_that_find_first_returns_a_contact(self, xivo_user_uuid): - engine = database.PersonalContactSearchEngine(Session, first_match_columns=['number']) + engine = database.PersonalContactSearchEngine( + Session, first_match_columns=['number'] + ) self._insert_personal_contacts( - xivo_user_uuid, self.contact_1, self.contact_2, self.contact_3, + xivo_user_uuid, self.contact_1, self.contact_2, self.contact_3 ) result = engine.find_first_personal_contact(xivo_user_uuid, '5555550001') - assert_that(result, contains(any_of(expected(self.contact_2), expected(self.contact_3)))) + assert_that( + result, contains(any_of(expected(self.contact_2), expected(self.contact_3))) + ) @with_user_uuid - def test_that_listing_personal_contacts_returns_the_searched_contacts(self, xivo_user_uuid): - engine = database.PersonalContactSearchEngine(Session, searched_columns=['firstname']) + def test_that_listing_personal_contacts_returns_the_searched_contacts( + self, xivo_user_uuid + ): + engine = database.PersonalContactSearchEngine( + Session, searched_columns=['firstname'] + ) - ids = self._insert_personal_contacts(xivo_user_uuid, self.contact_1, self.contact_2) + ids = self._insert_personal_contacts( + xivo_user_uuid, self.contact_1, self.contact_2 + ) result = engine.list_personal_contacts(xivo_user_uuid, ids) - assert_that(result, contains_inanyorder( - expected(self.contact_1), - expected(self.contact_2), - )) + assert_that( + result, + contains_inanyorder(expected(self.contact_1), expected(self.contact_2)), + ) result = engine.list_personal_contacts(xivo_user_uuid, ids[:1]) assert_that(result, contains(expected(self.contact_1))) @@ -1267,21 +1285,27 @@ def test_that_listing_personal_contacts_returns_the_searched_contacts(self, xivo @with_user_uuid @with_user_uuid - def test_that_listing_personal_contacts_only_the_users_contact(self, uuid_1, uuid_2): - engine = database.PersonalContactSearchEngine(Session, searched_columns=['firstname']) + def test_that_listing_personal_contacts_only_the_users_contact( + self, uuid_1, uuid_2 + ): + engine = database.PersonalContactSearchEngine( + Session, searched_columns=['firstname'] + ) ids_1 = self._insert_personal_contacts(uuid_1, self.contact_1, self.contact_2) ids_2 = self._insert_personal_contacts(uuid_2, self.contact_1, self.contact_3) result = engine.list_personal_contacts(uuid_1, ids_1) - assert_that(result, contains_inanyorder( - expected(self.contact_1), expected(self.contact_2))) + assert_that( + result, + contains_inanyorder(expected(self.contact_1), expected(self.contact_2)), + ) result = engine.list_personal_contacts(uuid_2, ids_2) - assert_that(result, contains_inanyorder( - expected(self.contact_1), - expected(self.contact_3), - )) + assert_that( + result, + contains_inanyorder(expected(self.contact_1), expected(self.contact_3)), + ) result = engine.list_personal_contacts(uuid_1, ids_2) assert_that(result, empty()) @@ -1291,7 +1315,9 @@ def test_that_listing_personal_contacts_only_the_users_contact(self, uuid_1, uui @with_user_uuid def test_that_searching_for_a_contact_returns_its_fields(self, xivo_user_uuid): - engine = database.PersonalContactSearchEngine(Session, searched_columns=['firstname']) + engine = database.PersonalContactSearchEngine( + Session, searched_columns=['firstname'] + ) self._insert_personal_contacts(xivo_user_uuid, self.contact_1, self.contact_2) @@ -1303,7 +1329,9 @@ def test_that_searching_for_a_contact_returns_its_fields(self, xivo_user_uuid): @with_user_uuid def test_that_find_searches_only_in_searched_columns(self, xivo_user_uuid): - engine = database.PersonalContactSearchEngine(Session, searched_columns=['lastname']) + engine = database.PersonalContactSearchEngine( + Session, searched_columns=['lastname'] + ) self._insert_personal_contacts(xivo_user_uuid, self.contact_1, self.contact_2) @@ -1323,7 +1351,6 @@ def test_that_no_searched_columns_does_not_search(self, xivo_user_uuid): class TestProfileCRUD(_BaseTest): - @fixtures.display(tenant_uuid=TENANT_UUID) @fixtures.source(tenant_uuid=TENANT_UUID) @fixtures.source(tenant_uuid=TENANT_UUID) @@ -1335,43 +1362,38 @@ def test_create_no_error(self, source_2, source_1, display): 'display': {'uuid': display['uuid']}, 'services': { 'lookup': { - 'sources': [ - {'uuid': source_1['uuid']}, - {'uuid': source_2['uuid']}, - ], + 'sources': [{'uuid': source_1['uuid']}, {'uuid': source_2['uuid']}], 'timeout': 5, }, - 'reverse': { - 'sources': [{'uuid': source_2['uuid']}], - 'timeout': 0.5, - }, - } + 'reverse': {'sources': [{'uuid': source_2['uuid']}], 'timeout': 0.5}, + }, } result = self.profile_crud.create(body) try: - assert_that(result, has_entries( - uuid=uuid_(), - tenant_uuid=TENANT_UUID, - name=name, - display=has_entries(uuid=display['uuid']), - services=has_entries( - lookup=has_entries( - sources=contains( - has_entries(uuid=source_1['uuid']), - has_entries(uuid=source_2['uuid']), + assert_that( + result, + has_entries( + uuid=uuid_(), + tenant_uuid=TENANT_UUID, + name=name, + display=has_entries(uuid=display['uuid']), + services=has_entries( + lookup=has_entries( + sources=contains( + has_entries(uuid=source_1['uuid']), + has_entries(uuid=source_2['uuid']), + ), + timeout=5, ), - timeout=5, - ), - reverse=has_entries( - sources=contains( - has_entries(uuid=source_2['uuid']), + reverse=has_entries( + sources=contains(has_entries(uuid=source_2['uuid'])), + timeout=0.5, ), - timeout=0.5, ), ), - )) + ) finally: self.profile_crud.delete(None, result['uuid']) @@ -1398,9 +1420,9 @@ def test_create_unknown_source(self, display): 'display_uuid': None, 'services': { 'lookup': { - 'sources': [{'uuid': 'eb124746-09be-44db-b01d-5b7dc1ea59a3'}], - }, - } + 'sources': [{'uuid': 'eb124746-09be-44db-b01d-5b7dc1ea59a3'}] + } + }, } assert_that( @@ -1412,11 +1434,7 @@ def test_create_unknown_source(self, display): 'tenant_uuid': new_uuid(), 'name': 'profile', 'display_uuid': None, - 'services': { - 'lookup': { - 'sources': [{'id': 42}], - }, - } + 'services': {'lookup': {'sources': [{'id': 42}]}}, } assert_that( @@ -1427,9 +1445,7 @@ def test_create_unknown_source(self, display): @fixtures.display( uuid='b76f21a2-c1ab-4f4c-b71e-dac6c7c18275', tenant_uuid='f537dcbf-2504-428f-967d-503cf7cbb66d', - columns=[ - {'title': 'Firstname', 'field': 'firstname'}, - ], + columns=[{'title': 'Firstname', 'field': 'firstname'}], ) @fixtures.source( uuid='91c48535-5104-4052-9b85-7a3b211ea1b0', @@ -1452,9 +1468,7 @@ def test_create_unknown_source(self, display): 'timeout': 3, }, 'reverse': { - 'sources': [ - {'uuid': '91c48535-5104-4052-9b85-7a3b211ea1b0'}, - ], + 'sources': [{'uuid': '91c48535-5104-4052-9b85-7a3b211ea1b0'}], 'timeout': 0.5, }, }, @@ -1464,27 +1478,36 @@ def test_get_detailed(self, profile, source_2, source_1, display): result = self.profile_crud.get([tenant_uuid], profile['uuid']) - assert_that(result, has_entries( - uuid=profile['uuid'], - name=profile['name'], - tenant_uuid=profile['tenant_uuid'], - display=display, - services=has_entries( - lookup=has_entries( - sources=contains_inanyorder( - has_entries(uuid=source_1['uuid'], backend=source_1['backend']), - has_entries(uuid=source_2['uuid'], backend=source_2['backend']), + assert_that( + result, + has_entries( + uuid=profile['uuid'], + name=profile['name'], + tenant_uuid=profile['tenant_uuid'], + display=display, + services=has_entries( + lookup=has_entries( + sources=contains_inanyorder( + has_entries( + uuid=source_1['uuid'], backend=source_1['backend'] + ), + has_entries( + uuid=source_2['uuid'], backend=source_2['backend'] + ), + ), + timeout=3, ), - timeout=3, - ), - reverse=has_entries( - sources=contains_inanyorder( - has_entries(uuid=source_1['uuid'], backend=source_1['backend']), + reverse=has_entries( + sources=contains_inanyorder( + has_entries( + uuid=source_1['uuid'], backend=source_1['backend'] + ) + ), + timeout=0.5, ), - timeout=0.5, ), ), - )) + ) @fixtures.profile( name='one', @@ -1562,7 +1585,9 @@ def test_delete(self, profile): ) assert_that( - calling(self.profile_crud.delete).with_args([unknown_uuid], profile['uuid']), + calling(self.profile_crud.delete).with_args( + [unknown_uuid], profile['uuid'] + ), raises(exception.NoSuchProfileAPIException), ) @@ -1572,6 +1597,8 @@ def test_delete(self, profile): ) assert_that( - calling(self.profile_crud.delete).with_args([profile['tenant_uuid']], profile['uuid']), + calling(self.profile_crud.delete).with_args( + [profile['tenant_uuid']], profile['uuid'] + ), not_(raises(Exception)), ) diff --git a/integration_tests/suite/test_database_reconnect.py b/integration_tests/suite/test_database_reconnect.py index c049f645..00583481 100644 --- a/integration_tests/suite/test_database_reconnect.py +++ b/integration_tests/suite/test_database_reconnect.py @@ -1,10 +1,7 @@ # Copyright 2018-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - equal_to, -) +from hamcrest import assert_that, equal_to from .helpers.base import BaseDirdIntegrationTest from .helpers.constants import VALID_TOKEN_MAIN_TENANT diff --git a/integration_tests/suite/test_dird_phonebook_backend.py b/integration_tests/suite/test_dird_phonebook_backend.py index 9026025f..93da356a 100644 --- a/integration_tests/suite/test_dird_phonebook_backend.py +++ b/integration_tests/suite/test_dird_phonebook_backend.py @@ -36,9 +36,7 @@ def teardown_module(): def _new_contact(firstname, lastname): random_number = ''.join(random.choice(string.digits) for _ in range(10)) - return {'firstname': firstname, - 'lastname': lastname, - 'number': random_number} + return {'firstname': firstname, 'lastname': lastname, 'number': random_number} contact_bodies = [ @@ -54,20 +52,25 @@ def _new_contact(firstname, lastname): class TestPhonebookBackend(unittest.TestCase): - def setUp(self): global contacts self.tenant_uuid = str(uuid4()) self.tenant = 'rowling' self.auth_client = Mock() - self.auth_client.tenants.list.return_value = {'items': [{'uuid': self.tenant_uuid}]} + self.auth_client.tenants.list.return_value = { + 'items': [{'uuid': self.tenant_uuid}] + } self.token_renewer = Mock() self.phonebook_crud = database.PhonebookCRUD(Session) self.phonebook_contact_crud = database.PhonebookContactCRUD(Session) - self.phonebook = self.phonebook_crud.create(self.tenant_uuid, {'name': 'hogwarts'}) + self.phonebook = self.phonebook_crud.create( + self.tenant_uuid, {'name': 'hogwarts'} + ) contacts = [ - self.phonebook_contact_crud.create(self.tenant_uuid, self.phonebook['id'], c) + self.phonebook_contact_crud.create( + self.tenant_uuid, self.phonebook['id'], c + ) for c in contact_bodies ] ( @@ -110,6 +113,8 @@ def test_that_first_match_returns_a_contact(self): assert_that(result, equal_to(self.draco)) def test_that_list_returns_the_contacts(self): - result = self.backend.list([self.hermione['id'], self.harry['id'], self.ron['id']]) + result = self.backend.list( + [self.hermione['id'], self.harry['id'], self.ron['id']] + ) assert_that(result, contains_inanyorder(self.hermione, self.harry, self.ron)) diff --git a/integration_tests/suite/test_displays.py b/integration_tests/suite/test_displays.py index 7d70f269..19688527 100644 --- a/integration_tests/suite/test_displays.py +++ b/integration_tests/suite/test_displays.py @@ -32,7 +32,6 @@ class BaseDisplayTestCase(BaseDirdIntegrationTest): class TestDelete(BaseDisplayTestCase): - @fixtures.display() def test_delete(self, display): assert_that( @@ -42,7 +41,9 @@ def test_delete(self, display): assert_that( calling(self.client.displays.delete).with_args(display['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) @fixtures.display(token=VALID_TOKEN_MAIN_TENANT) @@ -53,21 +54,27 @@ def test_multi_tenant(self, sub, main): assert_that( calling(sub_tenant_client.displays.delete).with_args(main['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(main_tenant_client.displays.delete).with_args( main['uuid'], tenant_uuid=SUB_TENANT ), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(sub_tenant_client.displays.delete).with_args( - main['uuid'], tenant_uuid=MAIN_TENANT, + main['uuid'], tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) assert_that( @@ -77,7 +84,6 @@ def test_multi_tenant(self, sub, main): class TestGet(BaseDisplayTestCase): - @fixtures.display() def test_get(self, display): response = self.client.displays.get(display['uuid']) @@ -85,7 +91,9 @@ def test_get(self, display): assert_that( calling(self.client.displays.delete).with_args(UNKNOWN_UUID), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) @fixtures.display(token=VALID_TOKEN_MAIN_TENANT) @@ -101,30 +109,37 @@ def test_multi_tenant(self, sub, main): calling(main_tenant_client.displays.get).with_args( main['uuid'], tenant_uuid=SUB_TENANT ), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(sub_tenant_client.displays.get).with_args(main['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(sub_tenant_client.displays.get).with_args( - main['uuid'], tenant_uuid=MAIN_TENANT, + main['uuid'], tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) class TestList(BaseDisplayTestCase): - @fixtures.display(name='abc') @fixtures.display(name='bcd') @fixtures.display(name='cde') def test_search(self, c, b, a): result = self.client.displays.list() - self.assert_list_result(result, contains_inanyorder(a, b, c), total=3, filtered=3) + self.assert_list_result( + result, contains_inanyorder(a, b, c), total=3, filtered=3 + ) result = self.client.displays.list(name='abc') self.assert_list_result(result, contains(a), total=3, filtered=1) @@ -146,7 +161,9 @@ def test_multi_tenant(self, c, b, a): self.assert_list_result(result, contains_inanyorder(a, b), total=2, filtered=2) result = main_tenant_client.displays.list(recurse=True) - self.assert_list_result(result, contains_inanyorder(a, b, c), total=3, filtered=3) + self.assert_list_result( + result, contains_inanyorder(a, b, c), total=3, filtered=3 + ) result = main_tenant_client.displays.list(tenant_uuid=SUB_TENANT, recurse=True) self.assert_list_result(result, contains_inanyorder(c), total=1, filtered=1) @@ -159,7 +176,9 @@ def test_multi_tenant(self, c, b, a): assert_that( calling(sub_tenant_client.displays.list).with_args(tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) @fixtures.display(name='abc') @@ -180,7 +199,6 @@ def test_pagination(self, c, b, a): class TestPost(BaseDisplayTestCase): - def test_invalid_bodies(self): invalid_bodies = [ {}, @@ -197,11 +215,7 @@ def test_valid_post(self): body = { 'name': 'display', 'columns': [ - { - 'field': 'fn', - 'title': 'Firstname', - 'default': '', - }, + {'field': 'fn', 'title': 'Firstname', 'default': ''}, { 'field': 'mobile', 'title': 'Mobile', @@ -213,26 +227,29 @@ def test_valid_post(self): } with self.create(self.client, body) as display: - assert_that(display, has_entries( - uuid=uuid_(), - tenant_uuid=MAIN_TENANT, - columns=contains( - has_entries( - field='fn', - title='Firstname', - default='', - type=None, - number_display=None, - ), - has_entries( - field='mobile', - title='Mobile', - type='number', - number_display='{firstname} (Mobile)', - default=None, + assert_that( + display, + has_entries( + uuid=uuid_(), + tenant_uuid=MAIN_TENANT, + columns=contains( + has_entries( + field='fn', + title='Firstname', + default='', + type=None, + number_display=None, + ), + has_entries( + field='mobile', + title='Mobile', + type='number', + number_display='{firstname} (Mobile)', + default=None, + ), ), ), - )) + ) def test_multi_tenant(self): body = {'name': 'foo', 'columns': [{'field': 'fn'}]} @@ -241,8 +258,12 @@ def test_multi_tenant(self): sub_tenant_client = self.get_client(VALID_TOKEN_SUB_TENANT) assert_that( - calling(sub_tenant_client.displays.create).with_args(body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))) + calling(sub_tenant_client.displays.create).with_args( + body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.create(main_tenant_client, body, tenant_uuid=SUB_TENANT) as display: @@ -273,17 +294,12 @@ def create(self, client, *args, **kwargs): class TestPut(BaseDisplayTestCase): - def setUp(self): super().setUp() self.valid_body = { 'name': 'display', 'columns': [ - { - 'field': 'fn', - 'title': 'Firstname', - 'default': '', - }, + {'field': 'fn', 'title': 'Firstname', 'default': ''}, { 'field': 'mobile', 'title': 'Mobile', @@ -299,19 +315,24 @@ def test_put(self, display): self.client.displays.edit(display['uuid'], self.valid_body) result = self.client.displays.get(display['uuid']) - assert_that(result, has_entries( - uuid=display['uuid'], - tenant_uuid=display['tenant_uuid'], - name=self.valid_body['name'], - columns=contains( - has_entries(self.valid_body['columns'][0]), - has_entries(self.valid_body['columns'][1]), + assert_that( + result, + has_entries( + uuid=display['uuid'], + tenant_uuid=display['tenant_uuid'], + name=self.valid_body['name'], + columns=contains( + has_entries(self.valid_body['columns'][0]), + has_entries(self.valid_body['columns'][1]), + ), ), - )) + ) assert_that( calling(self.client.displays.edit).with_args(UNKNOWN_UUID, self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) @fixtures.display() @@ -349,25 +370,35 @@ def test_put_multi_tenant(self, sub, main): ) assert_that( - calling(sub_tenant_client.displays.edit).with_args(main['uuid'], self.valid_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + calling(sub_tenant_client.displays.edit).with_args( + main['uuid'], self.valid_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(sub_tenant_client.displays.edit).with_args( - main['uuid'], self.valid_body, tenant_uuid=MAIN_TENANT, + main['uuid'], self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) assert_that( calling(main_tenant_client.displays.edit).with_args( - main['uuid'], self.valid_body, tenant_uuid=SUB_TENANT, + main['uuid'], self.valid_body, tenant_uuid=SUB_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) assert_that( - calling(main_tenant_client.displays.edit).with_args(sub['uuid'], self.valid_body), + calling(main_tenant_client.displays.edit).with_args( + sub['uuid'], self.valid_body + ), not_(raises(Exception)), ) diff --git a/integration_tests/suite/test_favorites.py b/integration_tests/suite/test_favorites.py index 0c6a6161..e627d11e 100644 --- a/integration_tests/suite/test_favorites.py +++ b/integration_tests/suite/test_favorites.py @@ -2,19 +2,10 @@ # SPDX-License-Identifier: GPL-3.0-or-later import uuid -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - equal_to, - has_entry, -) +from hamcrest import assert_that, contains, contains_inanyorder, equal_to, has_entry from xivo_test_helpers.bus import BusClient from xivo_test_helpers import until -from xivo_test_helpers.auth import ( - AuthClient as MockAuthClient, - MockUserToken, -) +from xivo_test_helpers.auth import AuthClient as MockAuthClient, MockUserToken from .helpers.base import ( BaseDirdIntegrationTest, @@ -22,11 +13,7 @@ PersonalOnlyTestCase, ) from .helpers.config import new_csv_with_multiple_displays_config -from .helpers.constants import ( - MAIN_TENANT, - TENANT_UUID_2, - VALID_TOKEN_MAIN_TENANT, -) +from .helpers.constants import MAIN_TENANT, TENANT_UUID_2, VALID_TOKEN_MAIN_TENANT class _BaseMultiTokenFavoriteTest(BaseDirdIntegrationTest): @@ -45,13 +32,13 @@ def setUpClass(cls): } mock_auth_client = MockAuthClient('localhost', cls.service_port(9497, 'auth')) user_token_1 = MockUserToken.some_token( - metadata={'tenant_uuid': tenants['items'][0]['uuid']}, + metadata={'tenant_uuid': tenants['items'][0]['uuid']} ) user_token_2 = MockUserToken.some_token( - metadata={'tenant_uuid': tenants['items'][1]['uuid']}, + metadata={'tenant_uuid': tenants['items'][1]['uuid']} ) user_token_3 = MockUserToken.some_token( - metadata={'tenant_uuid': tenants['items'][0]['uuid']}, + metadata={'tenant_uuid': tenants['items'][0]['uuid']} ) mock_auth_client.set_token(user_token_1) mock_auth_client.set_token(user_token_2) @@ -63,34 +50,53 @@ def setUpClass(cls): class TestFavorites(_BaseMultiTokenFavoriteTest): - def test_that_removed_favorites_are_not_listed(self): - with self.favorite('my_csv', '1', token=self.token_1), \ - self.favorite('my_csv', '2', token=self.token_1), \ - self.favorite('my_csv', '3', token=self.token_1): + with self.favorite('my_csv', '1', token=self.token_1), self.favorite( + 'my_csv', '2', token=self.token_1 + ), self.favorite('my_csv', '3', token=self.token_1): self.delete_favorite('my_csv', '2', token=self.token_1) result = self.favorites('default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)), - has_entry('column_values', contains('Charles', 'CCC', '555123555', True)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', True) + ), + has_entry( + 'column_values', contains('Charles', 'CCC', '555123555', True) + ), + ), + ) def test_that_favorites_are_only_visible_for_the_same_token(self): - with self.favorite('my_csv', '1', token=self.token_1), \ - self.favorite('my_csv', '2', token=self.token_1), \ - self.favorite('my_csv', '3', token=self.token_3): + with self.favorite('my_csv', '1', token=self.token_1), self.favorite( + 'my_csv', '2', token=self.token_1 + ), self.favorite('my_csv', '3', token=self.token_3): result = self.favorites('default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)), - has_entry('column_values', contains('Bob', 'BBB', '5555551234', True)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', True) + ), + has_entry('column_values', contains('Bob', 'BBB', '5555551234', True)), + ), + ) def test_that_favorites_are_saved_across_dird_restart(self): with self.favorite('my_csv', '1', token=self.token_1): result = self.favorites('default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', True) + ) + ), + ) self._run_cmd('docker-compose kill dird') self._run_cmd('docker-compose rm -f dird') @@ -98,24 +104,39 @@ def test_that_favorites_are_saved_across_dird_restart(self): result = self.favorites('default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', True) + ) + ), + ) def test_that_favorites_lookup_results_show_favorites(self): result = self.lookup('Ali', 'default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', False) + ) + ), + ) with self.favorite('my_csv', '1', token=self.token_1): result = self.lookup('Ali', 'default', token=self.token_1) - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', 'AAA', '5555555555', True)) + ), + ) class TestRemovingFavoriteAlreadyInexistant(CSVWithMultipleDisplayTestCase): - def test_that_removing_an_inexisting_favorite_returns_404(self): result = self.delete_favorite_result( 'unknown_source', 'unknown_contact', token=VALID_TOKEN_MAIN_TENANT @@ -125,33 +146,42 @@ def test_that_removing_an_inexisting_favorite_returns_404(self): class TestFavoritesInPersonalResults(PersonalOnlyTestCase): - def test_that_personal_list_results_show_favorites(self): - with self.personal({'firstname': 'Alice'}), \ - self.personal({'firstname': 'Bob'}) as bob, \ - self.personal({'firstname': 'Charlie'}): + with self.personal({'firstname': 'Alice'}), self.personal( + {'firstname': 'Bob'} + ) as bob, self.personal({'firstname': 'Charlie'}): result = self.get_personal_with_profile('default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', None, None, False)), - has_entry('column_values', contains('Bob', None, None, False)), - has_entry('column_values', contains('Charlie', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', None, None, False)), + has_entry('column_values', contains('Bob', None, None, False)), + has_entry('column_values', contains('Charlie', None, None, False)), + ), + ) with self.favorite('personal', bob['id']): personal = self.get_personal_with_profile('default') - assert_that(personal['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', None, None, False)), - has_entry('column_values', contains('Bob', None, None, True)), - has_entry('column_values', contains('Charlie', None, None, False)))) + assert_that( + personal['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', None, None, False)), + has_entry('column_values', contains('Bob', None, None, True)), + has_entry('column_values', contains('Charlie', None, None, False)), + ), + ) def test_that_favorites_list_results_accept_personal(self): with self.personal({'firstname': 'Alice'}) as alice: with self.favorite('personal', alice['id']): favorites = self.favorites('default') - assert_that(favorites['results'], contains( - has_entry('column_values', contains('Alice', None, None, True)))) + assert_that( + favorites['results'], + contains(has_entry('column_values', contains('Alice', None, None, True))), + ) def test_that_removed_favorited_personal_are_not_listed_anymore(self): with self.personal({'firstname': 'Alice'}) as alice: @@ -163,7 +193,6 @@ def test_that_removed_favorited_personal_are_not_listed_anymore(self): class TestFavoritesBusEvents(PersonalOnlyTestCase): - @classmethod def setUpClass(cls): super().setUpClass() @@ -175,11 +204,10 @@ def setUpClass(cls): } mock_auth_client = MockAuthClient('localhost', cls.service_port(9497, 'auth')) user_token_1 = MockUserToken.some_token( - metadata={'tenant_uuid': tenants['items'][0]['uuid']}, + metadata={'tenant_uuid': tenants['items'][0]['uuid']} ) user_token_2 = MockUserToken.some_token( - - metadata={'tenant_uuid': tenants['items'][1]['uuid']}, + metadata={'tenant_uuid': tenants['items'][1]['uuid']} ) mock_auth_client.set_token(user_token_1) mock_auth_client.set_token(user_token_2) diff --git a/integration_tests/suite/test_https.py b/integration_tests/suite/test_https.py index 199c4efd..8c0872bf 100644 --- a/integration_tests/suite/test_https.py +++ b/integration_tests/suite/test_https.py @@ -3,10 +3,7 @@ import time -from hamcrest import ( - assert_that, - contains_string, -) +from hamcrest import assert_that, contains_string from .helpers.base import DirdAssetRunningTestCase @@ -25,7 +22,10 @@ def test_given_inexisting_SSL_certificate_when_dird_starts_then_dird_stops(self) self.fail('wazo-dird did not stop while missing SSL certificate') log = self.service_logs() - assert_that(log, contains_string("No such file or directory: '/tmp/ssl/dird/server.crt'")) + assert_that( + log, + contains_string("No such file or directory: '/tmp/ssl/dird/server.crt'"), + ) class TestHTTPSMissingPrivateKey(DirdAssetRunningTestCase): @@ -42,4 +42,7 @@ def test_given_inexisting_SSL_private_key_when_dird_starts_then_dird_stops(self) self.fail('wazo-dird did not stop while missing SSL private key') log = self.service_logs() - assert_that(log, contains_string("No such file or directory: '/tmp/ssl/dird/server.key'")) + assert_that( + log, + contains_string("No such file or directory: '/tmp/ssl/dird/server.key'"), + ) diff --git a/integration_tests/suite/test_ldap_backend.py b/integration_tests/suite/test_ldap_backend.py index 0af09198..dfacc813 100644 --- a/integration_tests/suite/test_ldap_backend.py +++ b/integration_tests/suite/test_ldap_backend.py @@ -40,27 +40,30 @@ def __init__(self, ldap_uri): self._ldap_obj.simple_bind_s(self.ADMIN_DN, self.ADMIN_PASSWORD) def add_ou_quebec(self): - modlist = addModlist({ - 'objectClass': [b'organizationalUnit'], - 'ou': [b'quebec'], - }) + modlist = addModlist( + {'objectClass': [b'organizationalUnit'], 'ou': [b'quebec']} + ) self._ldap_obj.add_s(self.QUEBEC_DN, modlist) def add_contact(self, contact): cn = '{} {}'.format(contact.firstname, contact.lastname) dn = 'cn={},{}'.format(cn, self.QUEBEC_DN) - modlist = addModlist({ - 'objectClass': [b'inetOrgPerson'], - 'cn': [cn.encode('utf-8')], - 'givenName': [contact.firstname.encode('utf-8')], - 'sn': [contact.lastname.encode('utf-8')], - 'telephoneNumber': [contact.number.encode('utf-8')], - 'l': [contact.city.encode('utf-8')], - }) + modlist = addModlist( + { + 'objectClass': [b'inetOrgPerson'], + 'cn': [cn.encode('utf-8')], + 'givenName': [contact.firstname.encode('utf-8')], + 'sn': [contact.lastname.encode('utf-8')], + 'telephoneNumber': [contact.number.encode('utf-8')], + 'l': [contact.city.encode('utf-8')], + } + ) self._ldap_obj.add_s(dn, modlist) - search_dn, result = self._ldap_obj.search_s(dn, ldap.SCOPE_BASE, attrlist=['entryUUID'])[0] + search_dn, result = self._ldap_obj.search_s( + dn, ldap.SCOPE_BASE, attrlist=['entryUUID'] + )[0] return result['entryUUID'][0].decode('utf-8') @@ -110,20 +113,26 @@ def setUpClass(cls): def test_lookup_on_cn(self): result = self.lookup('Ali', 'default') - assert_that(result['results'][0]['column_values'], - contains('Alice', 'Wonderland', '1001')) + assert_that( + result['results'][0]['column_values'], + contains('Alice', 'Wonderland', '1001'), + ) def test_lookup_on_telephone_number(self): result = self.lookup('1001', 'default') - assert_that(result['results'][0]['column_values'], - contains('Alice', 'Wonderland', '1001')) + assert_that( + result['results'][0]['column_values'], + contains('Alice', 'Wonderland', '1001'), + ) def test_lookup_with_non_ascii_characters(self): result = self.lookup('ç', 'default') - assert_that(result['results'][0]['column_values'], - contains('François', 'Hollande', '1004')) + assert_that( + result['results'][0]['column_values'], + contains('François', 'Hollande', '1004'), + ) def test_reverse_lookup(self): result = self.reverse('1001', 'default', VALID_UUID) @@ -141,9 +150,13 @@ def test_ldap_favorites(self): result = self.favorites('default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', 'Wonderland', '1001')), - has_entry('column_values', contains('Connor', 'Manson', '1003')))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', 'Wonderland', '1001')), + has_entry('column_values', contains('Connor', 'Manson', '1003')), + ), + ) class TestLDAPWithCustomFilter(BaseDirdIntegrationTest): @@ -172,8 +185,9 @@ def setUpClass(cls): def test_lookup_on_cn(self): result = self.lookup('charlé', 'default') - assert_that(result['results'][0]['column_values'], - contains('Charlé', 'Doe', '1003')) + assert_that( + result['results'][0]['column_values'], contains('Charlé', 'Doe', '1003') + ) def test_no_result_because_of_the_custom_filter(self): result = self.lookup('alice', 'default') diff --git a/integration_tests/suite/test_ldap_http.py b/integration_tests/suite/test_ldap_http.py index 76961fd0..15695c25 100644 --- a/integration_tests/suite/test_ldap_http.py +++ b/integration_tests/suite/test_ldap_http.py @@ -56,7 +56,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) def get_client(self, token=VALID_TOKEN_MAIN_TENANT): @@ -72,7 +72,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BaseLDAPCRUDTestCase): - @fixtures.ldap_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -82,7 +81,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.ldap_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -112,46 +113,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BaseLDAPCRUDTestCase): - @fixtures.ldap_source(name='abc') @fixtures.ldap_source(name='bcd') @fixtures.ldap_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.ldap_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.ldap_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.ldap_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.ldap_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.ldap_source(name='abc') @@ -160,38 +143,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.ldap_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.ldap_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.ldap_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.ldap_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.ldap_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -203,43 +170,26 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.ldap_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.ldap_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.ldap_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.ldap_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BaseLDAPCRUDTestCase): - def test_post(self): try: self.client.ldap_source.create({}) @@ -259,9 +209,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.ldap_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -271,28 +221,33 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.ldap_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.ldap_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.ldap_source.create).with_args(self.valid_body), + calling(sub_tenant_client.ldap_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BaseLDAPCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { @@ -301,9 +256,7 @@ def setUp(self): 'ldap_base_dn': 'ou=other,dc=wazo,dc=io', 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.ldap_source(name='foobar') @@ -311,12 +264,18 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.ldap_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( - calling(self.client.ldap_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + calling(self.client.ldap_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -335,7 +294,9 @@ def test_put(self, foobar, other): self.fail('Should have raised') assert_that( - calling(self.client.ldap_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.ldap_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -351,7 +312,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.ldap_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -362,9 +323,11 @@ def test_put_multi_tenant(self, sub, main): assert_that( calling(sub_tenant_client.ldap_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -375,13 +338,14 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.ldap_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.ldap_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) class TestGet(BaseLDAPCRUDTestCase): - @fixtures.ldap_source(name='foobar') def test_get(self, wazo): response = self.client.ldap_source.get(wazo['uuid']) diff --git a/integration_tests/suite/test_office365_backend.py b/integration_tests/suite/test_office365_backend.py index c5329430..c125b802 100644 --- a/integration_tests/suite/test_office365_backend.py +++ b/integration_tests/suite/test_office365_backend.py @@ -35,23 +35,13 @@ class BaseOffice365TestCase(DirdAssetRunningTestCase): MICROSOFT_EXTERNAL_AUTH = { "access_token": "an-access-token", "scope": "a-scope", - "token_expiration": 42 + "token_expiration": 42, } - LOOKUP_ARGS = { - 'xivo_user_uuid': 'a-xivo-uuid', - 'token': 'a-token', - } - FAVORITE_ARGS = { - 'xivo_user_uuid': 'a-xivo-uuid', - 'token': 'a-token', - } + LOOKUP_ARGS = {'xivo_user_uuid': 'a-xivo-uuid', 'token': 'a-token'} + FAVORITE_ARGS = {'xivo_user_uuid': 'a-xivo-uuid', 'token': 'a-token'} - WARIO = { - 'givenName': 'Wario', - 'surname': 'Bros', - 'mobilePhone': '', - } + WARIO = {'givenName': 'Wario', 'surname': 'Bros', 'mobilePhone': ''} def setUp(self): super().setUp() @@ -64,21 +54,21 @@ def setUp(self): } self.client = DirdClient(**dird_config) self.source = self.client.backends.create_source( - backend=self.BACKEND, - body=self.config(), + backend=self.BACKEND, body=self.config() + ) + self.display = self.client.displays.create( + {'name': 'display', 'columns': [{'field': 'firstname'}]} + ) + self.profile = self.client.profiles.create( + { + 'name': 'default', + 'display': self.display, + 'services': {'lookup': {'sources': [self.source]}}, + } + ) + self.auth_client_mock = AuthMock( + host='0.0.0.0', port=self.service_port(9497, 'auth') ) - self.display = self.client.displays.create({ - 'name': 'display', - 'columns': [ - {'field': 'firstname'}, - ], - }) - self.profile = self.client.profiles.create({ - 'name': 'default', - 'display': self.display, - 'services': {'lookup': {'sources': [self.source]}}, - }) - self.auth_client_mock = AuthMock(host='0.0.0.0', port=self.service_port(9497, 'auth')) self.auth_client_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) def tearDown(self): @@ -86,8 +76,7 @@ def tearDown(self): self.client.profiles.delete(self.profile['uuid']) self.client.displays.delete(self.display['uuid']) self.client.backends.delete_source( - backend=self.BACKEND, - source_uuid=self.source['uuid'], + backend=self.BACKEND, source_uuid=self.source['uuid'] ) except requests.HTTPError: pass @@ -103,11 +92,7 @@ class BaseOffice365PluginTestCase(BaseOffice365TestCase): def setUp(self): self.auth_mock = AuthMock(host='0.0.0.0', port=self.service_port(9497, 'auth')) self.backend = BackendWrapper( - 'office365', - { - 'config': self.config(), - 'api': Mock() - } + 'office365', {'config': self.config(), 'api': Mock()} ) def tearDown(self): @@ -134,11 +119,7 @@ def config(self): 'email': '{emailAddresses[0][address]}', }, 'name': 'office365', - 'searched_columns': [ - "givenName", - "surname", - "businessPhones" - ], + 'searched_columns': ["givenName", "surname", "businessPhones"], 'type': 'office365', } @@ -147,33 +128,46 @@ def test_plugin_lookup(self): result = self.backend.search('war', self.LOOKUP_ARGS) - assert_that(result, contains(has_entries( - number='5555555555', - email='wbros@wazoquebec.onmicrosoft.com', - **self.WARIO - ))) + assert_that( + result, + contains( + has_entries( + number='5555555555', + email='wbros@wazoquebec.onmicrosoft.com', + **self.WARIO + ) + ), + ) def test_plugin_favorites(self): self.auth_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) result = self.backend.list(['an-id'], self.FAVORITE_ARGS) - assert_that(result, contains(has_entries( - number='5555555555', - email='wbros@wazoquebec.onmicrosoft.com', - **self.WARIO - ))) + assert_that( + result, + contains( + has_entries( + number='5555555555', + email='wbros@wazoquebec.onmicrosoft.com', + **self.WARIO + ) + ), + ) def test_plugin_reverse(self): self.auth_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) result = self.backend.first('5555555555', self.LOOKUP_ARGS) - assert_that(result, has_entries( - number='5555555555', - email='wbros@wazoquebec.onmicrosoft.com', - **self.WARIO - )) + assert_that( + result, + has_entries( + number='5555555555', + email='wbros@wazoquebec.onmicrosoft.com', + **self.WARIO + ), + ) class TestOffice365PluginWrongEndpoint(BaseOffice365PluginTestCase): @@ -224,11 +218,7 @@ class TestDirdOffice365Plugin(BaseOffice365TestCase): def config(self): return { - 'auth': { - 'host': 'auth', - 'port': 9497, - 'verify_certificate': False, - }, + 'auth': {'host': 'auth', 'port': 9497, 'verify_certificate': False}, 'endpoint': 'http://microsoft-mock:80/me/contacts', 'first_matched_columns': [], 'format_columns': { @@ -237,27 +227,24 @@ def config(self): 'number': "{businessPhones[0]}", }, 'name': 'office365', - 'searched_columns': [ - "givenName", - "surname", - "businessPhones" - ], + 'searched_columns': ["givenName", "surname", "businessPhones"], 'type': 'office365', } def setUp(self): super().setUp() - self.auth_client_mock = AuthMock(host='0.0.0.0', port=self.service_port(9497, 'auth')) + self.auth_client_mock = AuthMock( + host='0.0.0.0', port=self.service_port(9497, 'auth') + ) def test_given_microsoft_when_lookup_then_contacts_fetched(self): self.auth_client_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) result = self.client.directories.lookup(term='war', profile='default') - assert_that(result, has_entries( - results=contains( - has_entries(column_values=contains('Wario')), - ) - )) + assert_that( + result, + has_entries(results=contains(has_entries(column_values=contains('Wario')))), + ) def test_given_no_microsoft_when_lookup_then_no_result(self): self.auth_client_mock.reset_external_auth() @@ -271,35 +258,42 @@ def test_given_microsoft_source_when_get_all_contacts_then_contacts_fetched(self self.auth_client_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) result = self.client.backends.list_contacts_from_source( - backend=self.BACKEND, - source_uuid=self.source['uuid'], + backend=self.BACKEND, source_uuid=self.source['uuid'] + ) + + assert_that( + result, + has_entries( + total=1, + filtered=1, + items=contains( + has_entries( + displayName='Wario Bros', + surname='Bros', + businessPhones=['5555555555'], + givenName='Wario', + ) + ), + ), ) - assert_that(result, has_entries( - total=1, - filtered=1, - items=contains(has_entries( - displayName='Wario Bros', - surname='Bros', - businessPhones=['5555555555'], - givenName='Wario', - )), - )) - - def test_given_non_existing_microsoft_source_when_get_all_contacts_then_not_found(self): + def test_given_non_existing_microsoft_source_when_get_all_contacts_then_not_found( + self + ): self.auth_client_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) assert_that( calling(self.client.backends.list_contacts_from_source).with_args( - backend=self.BACKEND, - source_uuid='a-non-existing-source-uuid', + backend=self.BACKEND, source_uuid='a-non-existing-source-uuid' ), raises(requests.HTTPError).matching( has_property('response', has_properties('status_code', 404)) - ) + ), ) - def test_given_source_and_non_existing_tenant_when_get_all_contacts_then_not_found(self): + def test_given_source_and_non_existing_tenant_when_get_all_contacts_then_not_found( + self + ): self.auth_client_mock.set_external_auth(self.MICROSOFT_EXTERNAL_AUTH) assert_that( @@ -310,7 +304,7 @@ def test_given_source_and_non_existing_tenant_when_get_all_contacts_then_not_fou ), raises(requests.HTTPError).matching( has_property('response', has_properties('status_code', 404)) - ) + ), ) @@ -322,11 +316,7 @@ class TestDirdOffice365PluginNoEndpoint(BaseOffice365TestCase): def config(self): return { - 'auth': { - 'host': 'auth', - 'port': 9497, - 'verify_certificate': False, - }, + 'auth': {'host': 'auth', 'port': 9497, 'verify_certificate': False}, 'first_matched_columns': [], 'format_columns': { 'firstname': "{givenName}", @@ -335,21 +325,20 @@ def config(self): 'phone_mobile': "{mobilePhone}", }, 'name': 'office365', - 'searched_columns': [ - "givenName", - "surname", - "businessPhones" - ], + 'searched_columns': ["givenName", "surname", "businessPhones"], 'type': 'office365', } def test_given_microsoft_when_lookup_with_no_endpoint_then_no_error(self): - assert_that(self.source['endpoint'], equal_to( - 'https://graph.microsoft.com/v1.0/me/contacts' - )) assert_that( - calling(self.client.directories.lookup).with_args(term='war', profile='default'), - not_(raises(Exception)) + self.source['endpoint'], + equal_to('https://graph.microsoft.com/v1.0/me/contacts'), + ) + assert_that( + calling(self.client.directories.lookup).with_args( + term='war', profile='default' + ), + not_(raises(Exception)), ) @@ -361,11 +350,7 @@ class TestDirdOffice365PluginErrorEndpoint(BaseOffice365TestCase): def config(self): return { - 'auth': { - 'host': 'auth', - 'port': 9497, - 'verify_certificate': False, - }, + 'auth': {'host': 'auth', 'port': 9497, 'verify_certificate': False}, 'endpoint': 'http://microsoft-mock:80/me/contacts/error', 'first_matched_columns': [], 'format_columns': { @@ -382,19 +367,17 @@ def config(self): def test_given_microsoft_when_lookup_with_error_endpoint_then_no_error(self): assert_that( calling(self.client.directories.lookup).with_args( - term='war', - profile='default', + term='war', profile='default' ), - not_(raises(Exception)) + not_(raises(Exception)), ) def test_given_microsoft_when_fetch_all_contacts_with_error_endpoint(self): assert_that( calling(self.client.backends.list_contacts_from_source).with_args( - backend=self.BACKEND, - source_uuid=self.source['uuid'] + backend=self.BACKEND, source_uuid=self.source['uuid'] ), raises(requests.HTTPError).matching( has_property('response', has_properties('status_code', 503)) - ) + ), ) diff --git a/integration_tests/suite/test_personal.py b/integration_tests/suite/test_personal.py index 7f15c09b..3e89a826 100644 --- a/integration_tests/suite/test_personal.py +++ b/integration_tests/suite/test_personal.py @@ -21,15 +21,9 @@ ) from mock import ANY from xivo_bus.resources.user import event -from xivo_bus import ( - Publisher, - Marshaler, -) +from xivo_bus import Publisher, Marshaler from xivo_test_helpers import until -from xivo_test_helpers.auth import ( - AuthClient as MockAuthClient, - MockUserToken, -) +from xivo_test_helpers.auth import AuthClient as MockAuthClient, MockUserToken from .helpers.constants import ( MAIN_TENANT, @@ -39,14 +33,10 @@ VALID_TOKEN_2, ) -from .helpers.base import ( - BaseDirdIntegrationTest, - PersonalOnlyTestCase, -) +from .helpers.base import BaseDirdIntegrationTest, PersonalOnlyTestCase class TestListPersonal(PersonalOnlyTestCase): - def test_that_listing_empty_personal_returns_empty_list(self): result = self.list_personal() @@ -63,10 +53,9 @@ class TestDeletedUser(BaseDirdIntegrationTest): def setUp(self): super().setUp() bus_port = self.service_port(5672, 'rabbitmq') - bus_url = 'amqp://{username}:{password}@{host}:{port}//'.format(username='guest', - password='guest', - host='localhost', - port=bus_port) + bus_url = 'amqp://{username}:{password}@{host}:{port}//'.format( + username='guest', password='guest', host='localhost', port=bus_port + ) self._connection = kombu.Connection(bus_url) self._connection.connect() @@ -86,13 +75,14 @@ def _publish_user_deleted_event(self, uuid): msg = event.DeleteUserEvent(42, uuid) marshaler = Marshaler('the-xivo-uuid') exchange = kombu.Exchange('xivo', type='topic') - producer = kombu.Producer(self._connection, exchange=exchange, auto_declare=True) + producer = kombu.Producer( + self._connection, exchange=exchange, auto_declare=True + ) publisher = Publisher(producer, marshaler) publisher.publish(msg) class TestAddPersonal(PersonalOnlyTestCase): - def test_that_created_personal_has_an_id(self): alice = self.post_personal({'firstname': 'Alice'}) bob = self.post_personal({'firstname': 'Bob'}) @@ -105,9 +95,10 @@ def test_that_created_personal_are_listed(self): result = self.list_personal() - assert_that(result['items'], has_items( - has_entry('firstname', 'Alice'), - has_entry('firstname', 'Bob'))) + assert_that( + result['items'], + has_items(has_entry('firstname', 'Alice'), has_entry('firstname', 'Bob')), + ) def test_that_created_personal_with_non_ascii_are_listed(self): self.post_personal({'firstname': 'Alice', 'key': 'NonAsciiValue-é'}) @@ -115,10 +106,11 @@ def test_that_created_personal_with_non_ascii_are_listed(self): raw = self.list_personal() formatted = self.get_personal_with_profile('default') - assert_that(raw['items'], has_items( - has_entry('key', 'NonAsciiValue-é'))) - assert_that(formatted['results'], has_items( - has_entry('column_values', contains('Alice', None, None, False)))) + assert_that(raw['items'], has_items(has_entry('key', 'NonAsciiValue-é'))) + assert_that( + formatted['results'], + has_items(has_entry('column_values', contains('Alice', None, None, False))), + ) def test_that_adding_invalid_personal_returns_400(self): result = self.post_personal_result({'': 'invalid'}, VALID_TOKEN_MAIN_TENANT) @@ -127,31 +119,24 @@ def test_that_adding_invalid_personal_returns_400(self): def test_that_adding_duplicated_personal_returns_409(self): self.post_personal_result({'firstname': 'Alice'}, VALID_TOKEN_MAIN_TENANT) - result = self.post_personal_result({'firstname': 'Alice'}, VALID_TOKEN_MAIN_TENANT) + result = self.post_personal_result( + {'firstname': 'Alice'}, VALID_TOKEN_MAIN_TENANT + ) assert_that(result.status_code, equal_to(409)) def test_that_adding_personal_with_weird_attributes_is_ok(self): - self.post_personal({ - '%': '%', - '?': '?', - '#': '#', - '%': '%' - }) + self.post_personal({'%': '%', '?': '?', '#': '#', '%': '%'}) result = self.list_personal() - assert_that(result['items'], has_item( - has_entries({ - '%': '%', - '?': '?', - '#': '#', - '%': '%' - }))) + assert_that( + result['items'], + has_item(has_entries({'%': '%', '?': '?', '#': '#', '%': '%'})), + ) class TestRemovePersonal(PersonalOnlyTestCase): - def test_that_removing_unknown_personal_returns_404(self): result = self.delete_personal_result('unknown-id', VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(404)) @@ -164,13 +149,15 @@ def test_that_removed_personal_are_not_listed(self): result = self.list_personal() - assert_that(result['items'], contains_inanyorder( - has_entry('firstname', 'Alice'), - has_entry('firstname', 'Charlie'))) + assert_that( + result['items'], + contains_inanyorder( + has_entry('firstname', 'Alice'), has_entry('firstname', 'Charlie') + ), + ) class TestPurgePersonal(PersonalOnlyTestCase): - def test_that_purged_personal_are_empty(self): self.post_personal({'firstname': 'Alice'}) self.post_personal({'firstname': 'Bob'}) @@ -183,7 +170,6 @@ def test_that_purged_personal_are_empty(self): class TestPersonalPersistence(PersonalOnlyTestCase): - def test_that_personal_are_saved_across_dird_restart(self): self.post_personal({'firstname': 'Foo'}) @@ -198,23 +184,22 @@ def test_that_personal_are_saved_across_dird_restart(self): result_after = self.list_personal() assert_that(result_after['items'], contains(has_key('id'))) - assert_that(result_before['items'][0]['id'], equal_to(result_after['items'][0]['id'])) + assert_that( + result_before['items'][0]['id'], equal_to(result_after['items'][0]['id']) + ) class TestPersonalVisibility(PersonalOnlyTestCase): - @classmethod def setUpClass(cls): super().setUpClass() mock_auth_client = MockAuthClient('localhost', cls.service_port(9497, 'auth')) tenant_uuid = MAIN_TENANT valid_token_1 = MockUserToken.some_token( - token=VALID_TOKEN_1, - metadata={'tenant_uuid': tenant_uuid}, + token=VALID_TOKEN_1, metadata={'tenant_uuid': tenant_uuid} ) valid_token_2 = MockUserToken.some_token( - token=VALID_TOKEN_2, - metadata={'tenant_uuid': tenant_uuid}, + token=VALID_TOKEN_2, metadata={'tenant_uuid': tenant_uuid} ) mock_auth_client.set_token(valid_token_1) mock_auth_client.set_token(valid_token_2) @@ -228,15 +213,20 @@ def test_that_personal_are_only_visible_for_the_same_token(self): result_1 = self.list_personal(token=VALID_TOKEN_1) result_2 = self.list_personal(token=VALID_TOKEN_2) - assert_that(result_1['items'], contains_inanyorder(has_entry('firstname', 'Alice'), - has_entry('firstname', 'Bob'))) + assert_that( + result_1['items'], + contains_inanyorder( + has_entry('firstname', 'Alice'), has_entry('firstname', 'Bob') + ), + ) assert_that(result_2['items'], contains(has_entry('firstname', 'Charlie'))) class TestPersonalListWithProfile(PersonalOnlyTestCase): - def test_listing_personal_with_unknow_profile(self): - result = self.get_personal_with_profile_result('unknown', token=VALID_TOKEN_MAIN_TENANT) + result = self.get_personal_with_profile_result( + 'unknown', token=VALID_TOKEN_MAIN_TENANT + ) assert_that(result.status_code, equal_to(404)) @@ -251,13 +241,16 @@ def test_listing_personal_with_profile(self): result = self.get_personal_with_profile('default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', None, None, False)), - has_entry('column_values', contains('Bob', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', None, None, False)), + has_entry('column_values', contains('Bob', None, None, False)), + ), + ) class TestLookupPersonal(PersonalOnlyTestCase): - def setUp(self): super().setUp() self.post_personal({'firstname': 'Alice'}) @@ -266,43 +259,69 @@ def setUp(self): self.post_personal({'firstname': 'Etienne'}) self.post_personal({'firstname': 'john', 'lastname': 'john', 'company': 'john'}) self.post_personal({'firstname': 'empty-column', 'lastname': ''}) - self.post_personal({'firstname': 'Elice', 'lastname': 'Wowo', 'number': '123456'}) + self.post_personal( + {'firstname': 'Elice', 'lastname': 'Wowo', 'number': '123456'} + ) def test_that_lookup_includes_personal_contacts(self): result = self.lookup('ali', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Alice', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Alice', None, None, False)) + ), + ) def test_that_lookup_accepts_non_ascii_in_term(self): result = self.lookup('Céline', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Céline', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Céline', None, None, False)) + ), + ) def test_that_lookup_matches_query_ascii_with_result_non_ascii(self): result = self.lookup('celine', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Céline', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Céline', None, None, False)) + ), + ) def test_that_lookup_matches_query_non_ascii_with_result_ascii(self): result = self.lookup('étienne', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('Etienne', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('Etienne', None, None, False)) + ), + ) def test_that_lookup_does_not_return_duplicates_when_matching_multiple_fields(self): result = self.lookup('john', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('john', 'john', None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('john', 'john', None, False)) + ), + ) def test_that_lookup_returns_None_when_a_column_is_empty(self): result = self.lookup('empty', 'default') - assert_that(result['results'], contains_inanyorder( - has_entry('column_values', contains('empty-column', None, None, False)))) + assert_that( + result['results'], + contains_inanyorder( + has_entry('column_values', contains('empty-column', None, None, False)) + ), + ) def test_reverse_lookup_with_xivo_user_uuid(self): result = self.reverse('123456', 'default', VALID_UUID) @@ -316,7 +335,6 @@ def test_reverse_lookup_with_invalid_xivo_user_uuid(self): class TestEditPersonal(PersonalOnlyTestCase): - def test_that_edit_inexisting_personal_contact_returns_404(self): body = {'firstname': 'John', 'lastname': 'Doe'} result = self.put_personal_result('unknown-id', body, VALID_TOKEN_MAIN_TENANT) @@ -325,23 +343,26 @@ def test_that_edit_inexisting_personal_contact_returns_404(self): def test_that_edit_personal_contact_replaces_attributes(self): contact = self.post_personal({'firstname': 'Noémie', 'lastname': 'Narvidon'}) - put_result = self.put_personal(contact['id'], {'firstname': 'Nicolas', 'company': 'acme'}) + put_result = self.put_personal( + contact['id'], {'firstname': 'Nicolas', 'company': 'acme'} + ) assert_that(put_result, has_key('id')) assert_that(put_result, contains_inanyorder('id', 'firstname', 'company')) - assert_that(put_result, has_entries({ - 'firstname': 'Nicolas', - 'company': 'acme' - })) + assert_that( + put_result, has_entries({'firstname': 'Nicolas', 'company': 'acme'}) + ) list_result = self.list_personal() - assert_that(list_result['items'], contains(all_of( - contains_inanyorder('id', 'firstname', 'company'), - has_entries({ - 'firstname': 'Nicolas', - 'company': 'acme' - }) - ))) + assert_that( + list_result['items'], + contains( + all_of( + contains_inanyorder('id', 'firstname', 'company'), + has_entries({'firstname': 'Nicolas', 'company': 'acme'}), + ) + ), + ) def test_that_edit_cannot_duplicate_contacts(self): contact_1 = self.post_personal({'firstname': 'Noémie', 'lastname': 'Narvidon'}) @@ -354,14 +375,16 @@ def test_that_edit_cannot_duplicate_contacts(self): assert_that(put_result.status_code, equal_to(409)) list_result = self.list_personal() - assert_that(list_result['items'], contains_inanyorder( - {'id': ANY, 'firstname': 'Noémie', 'lastname': 'Narvidon'}, - {'id': ANY, 'firstname': 'Paul', 'lastname': 'Narvidon'}, - )) + assert_that( + list_result['items'], + contains_inanyorder( + {'id': ANY, 'firstname': 'Noémie', 'lastname': 'Narvidon'}, + {'id': ANY, 'firstname': 'Paul', 'lastname': 'Narvidon'}, + ), + ) class TestEditInvalidPersonal(PersonalOnlyTestCase): - def test_that_edit_personal_contact_with_invalid_values_return_404(self): contact = self.post_personal({'firstname': 'Ursule', 'lastname': 'Uparlende'}) @@ -374,7 +397,6 @@ def test_that_edit_personal_contact_with_invalid_values_return_404(self): class TestGetPersonal(PersonalOnlyTestCase): - def test_that_get_inexisting_personal_contact_returns_404(self): result = self.get_personal_result('unknown-id', VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(404)) @@ -384,14 +406,13 @@ def test_that_get_returns_all_attributes(self): result = self.get_personal(contact['id']) - assert_that(result, has_entries({ - 'firstname': 'Noémie', - 'lastname': 'Narvidon' - })) + assert_that( + result, has_entries({'firstname': 'Noémie', 'lastname': 'Narvidon'}) + ) def test_that_personal_api_is_symmetric(self): contact_post = self.post_personal( - {'firstname': 'Noémie', 'lastname': 'Narvidon', 'special-key': ''}, + {'firstname': 'Noémie', 'lastname': 'Narvidon', 'special-key': ''} ) contact_put = self.put_personal(contact_post['id'], contact_post) contact_get = self.get_personal(contact_post['id']) diff --git a/integration_tests/suite/test_personal_export.py b/integration_tests/suite/test_personal_export.py index 77106e14..88317a21 100644 --- a/integration_tests/suite/test_personal_export.py +++ b/integration_tests/suite/test_personal_export.py @@ -1,12 +1,7 @@ # Copyright 2015-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - contains_inanyorder, - equal_to, - matches_regexp, -) +from hamcrest import assert_that, contains_inanyorder, equal_to, matches_regexp from .helpers.base import BaseDirdIntegrationTest @@ -30,8 +25,13 @@ def test_that_export_full_returns_all_contacts(self): result = result.split('\r\n') assert_that(result[0], equal_to('firstname,id,lastname')) - assert_that(result[1:-1], contains_inanyorder(matches_regexp('Alice,[^,]*,Aldertion'), - matches_regexp('Bob,[^,]*,Bodkartan'))) + assert_that( + result[1:-1], + contains_inanyorder( + matches_regexp('Alice,[^,]*,Aldertion'), + matches_regexp('Bob,[^,]*,Bodkartan'), + ), + ) assert_that(result[-1], equal_to('')) def test_that_export_with_empty_values_returns_empty_strings(self): @@ -52,8 +52,12 @@ def test_that_export_full_mixes_all_headers(self): result = result.split('\r\n') assert_that(result[0], equal_to('firstname,id,lastname')) - assert_that(result[1:-1], contains_inanyorder(matches_regexp('Alice,[^,]*,'), - matches_regexp(',[^,]*,Bodkartan'))) + assert_that( + result[1:-1], + contains_inanyorder( + matches_regexp('Alice,[^,]*,'), matches_regexp(',[^,]*,Bodkartan') + ), + ) assert_that(result[-1], equal_to('')) def test_that_export_with_non_ascii_is_ok(self): @@ -73,6 +77,10 @@ def test_that_export_produces_the_same_output_as_import_with_empty_column(self): result = result.split('\r\n') assert_that(result[0], equal_to('firstname,id,lastname,special-key')) - assert_that(result[1:-1], contains_inanyorder(matches_regexp('john,[^,]*,doe,'), - matches_regexp('bob,[^,]*,martin,'))) + assert_that( + result[1:-1], + contains_inanyorder( + matches_regexp('john,[^,]*,doe,'), matches_regexp('bob,[^,]*,martin,') + ), + ) assert_that(result[-1], equal_to('')) diff --git a/integration_tests/suite/test_personal_http.py b/integration_tests/suite/test_personal_http.py index dbaae0ec..e71a589d 100644 --- a/integration_tests/suite/test_personal_http.py +++ b/integration_tests/suite/test_personal_http.py @@ -32,9 +32,7 @@ class BasePersonalCRUDTestCase(BaseDirdIntegrationTest): asset = 'all_routes' - valid_body = { - 'name': 'main', - } + valid_body = {'name': 'main'} @classmethod def setUpClass(cls): @@ -54,7 +52,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) def get_client(self, token=VALID_TOKEN_MAIN_TENANT): @@ -70,7 +68,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BasePersonalCRUDTestCase): - @fixtures.personal_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -80,7 +77,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.personal_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -110,46 +109,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BasePersonalCRUDTestCase): - @fixtures.personal_source(name='abc') @fixtures.personal_source(name='bcd') @fixtures.personal_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.personal_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.personal_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.personal_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.personal_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.personal_source(name='abc') @@ -158,38 +139,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.personal_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.personal_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.personal_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.personal_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.personal_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -201,54 +166,33 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.personal_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.personal_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.personal_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.personal_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BasePersonalCRUDTestCase): - def test_post(self): try: self.client.personal_source.create({}) except Exception as e: assert_that(e.response.status_code, equal_to(400)) assert_that( - e.response.json(), - has_entries( - message=ANY, - error_id='invalid-data', - ), + e.response.json(), has_entries(message=ANY, error_id='invalid-data') ) else: self.fail('Should have raised') @@ -256,9 +200,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.personal_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -268,37 +212,40 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.personal_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.personal_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.personal_source.create).with_args(self.valid_body), + calling(sub_tenant_client.personal_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BasePersonalCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { 'name': 'new', 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.personal_source(name='foobar') @@ -306,12 +253,18 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.personal_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( - calling(self.client.personal_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + calling(self.client.personal_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -319,17 +272,15 @@ def test_put(self, foobar, other): except Exception as e: assert_that(e.response.status_code, equal_to(400)) assert_that( - e.response.json(), - has_entries( - message=ANY, - error_id='invalid-data', - ), + e.response.json(), has_entries(message=ANY, error_id='invalid-data') ) else: self.fail('Should have raised') assert_that( - calling(self.client.personal_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.personal_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -343,7 +294,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.personal_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -353,10 +304,14 @@ def test_put_multi_tenant(self, sub, main): sub_tenant_client = self.get_client(VALID_TOKEN_SUB_TENANT) assert_that( - calling(sub_tenant_client.personal_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + calling(sub_tenant_client.personal_source.edit).with_args( + main['uuid'], sub + ), + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -367,13 +322,14 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.personal_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.personal_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) class TestGet(BasePersonalCRUDTestCase): - @fixtures.personal_source(name='foobar') def test_get(self, wazo): response = self.client.personal_source.get(wazo['uuid']) diff --git a/integration_tests/suite/test_personal_import.py b/integration_tests/suite/test_personal_import.py index d4904180..e0eb0817 100644 --- a/integration_tests/suite/test_personal_import.py +++ b/integration_tests/suite/test_personal_import.py @@ -25,43 +25,55 @@ def test_that_import_empty_returns_400(self): assert_that(result.status_code, equal_to(400)) def test_that_import_with_only_headers_return_400(self): - result = self.import_personal_result('firstname,lastname\n', VALID_TOKEN_MAIN_TENANT) + result = self.import_personal_result( + 'firstname,lastname\n', VALID_TOKEN_MAIN_TENANT + ) assert_that(result.status_code, equal_to(400)) def test_that_import_with_invalid_headers_return_400(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ ,lastname alice,ablskdfj bob,baseoirjl - ''') + ''' + ) result = self.import_personal_result(csv, VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(400)) def test_that_import_with_only_wrong_entries_return_400(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname alice bob - ''') + ''' + ) result = self.import_personal_result(csv, VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(400)) def test_that_import_ignores_superfluous_fields(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname alice,aldertion,field,field bob,bodkartan,field,field - ''') + ''' + ) result = self.import_personal_result(csv, VALID_TOKEN_MAIN_TENANT) assert_that(result.status_code, equal_to(400)) def test_that_import_wrong_encoding_returns_400(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname valérie,vladinski loïc,lorbantic - ''').encode('cp1252') - result = self.import_personal_result(csv, VALID_TOKEN_MAIN_TENANT, encoding='utf-8') + ''' + ).encode('cp1252') + result = self.import_personal_result( + csv, VALID_TOKEN_MAIN_TENANT, encoding='utf-8' + ) assert_that(result.status_code, equal_to(400)) @@ -70,18 +82,26 @@ class TestPersonalImportSuccess(BaseDirdIntegrationTest): asset = 'personal_only' def test_that_import_with_correct_data_appears_in_list(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname alice,aldertion bob,bodkartan - ''') + ''' + ) result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT) assert_that(result['failed'], contains()) - assert_that(result['created'], contains_inanyorder( - has_entries({'firstname': 'alice', 'lastname': 'aldertion'}), - has_entries({'firstname': 'bob', 'lastname': 'bodkartan'}))) - assert_that(result['created'], contains_inanyorder(*self.list_personal()['items'])) + assert_that( + result['created'], + contains_inanyorder( + has_entries({'firstname': 'alice', 'lastname': 'aldertion'}), + has_entries({'firstname': 'bob', 'lastname': 'bodkartan'}), + ), + ) + assert_that( + result['created'], contains_inanyorder(*self.list_personal()['items']) + ) class TestPersonalImportSomeFail(BaseDirdIntegrationTest): @@ -89,37 +109,49 @@ class TestPersonalImportSomeFail(BaseDirdIntegrationTest): asset = 'personal_only' def test_that_import_with_one_wrongly_formatted_creates_the_others(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname alice,aldertion i,love,commas,,,,,,,,,,,, bob,bodkartan i,too,love,commas,,,,,,,,,,,, - ''') + ''' + ) result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT) - assert_that(result['failed'], contains( - has_entry('line', 3), - has_entry('line', 5))) - assert_that(self.list_personal()['items'], contains_inanyorder( - has_entries({'firstname': 'alice', 'lastname': 'aldertion'}), - has_entries({'firstname': 'bob', 'lastname': 'bodkartan'}))) + assert_that( + result['failed'], contains(has_entry('line', 3), has_entry('line', 5)) + ) + assert_that( + self.list_personal()['items'], + contains_inanyorder( + has_entries({'firstname': 'alice', 'lastname': 'aldertion'}), + has_entries({'firstname': 'bob', 'lastname': 'bodkartan'}), + ), + ) def test_that_importing_a_contact_with_an_existing_uuid(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname alice - ''') + ''' + ) result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT) for user in result['created']: uuid = user['id'] break - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ id,firstname {},not alice 29d4aec1-db4c-4c67-80a0-b83136c58a47,bob - '''.format(uuid)) + '''.format( + uuid + ) + ) result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT) assert_that(result['failed'], contains(has_entry('line', 2))) @@ -130,14 +162,20 @@ class TestPersonalImportUTF8(BaseDirdIntegrationTest): asset = 'personal_only' def test_that_import_with_utf8_chars_is_valid(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname valérie,vidalzami - ''').encode('utf-8') + ''' + ).encode('utf-8') result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT) - assert_that(result['created'], contains_inanyorder( - has_entries({'firstname': 'valérie', 'lastname': 'vidalzami'}))) + assert_that( + result['created'], + contains_inanyorder( + has_entries({'firstname': 'valérie', 'lastname': 'vidalzami'}) + ), + ) class TestPersonalImportCP1252(BaseDirdIntegrationTest): @@ -145,11 +183,17 @@ class TestPersonalImportCP1252(BaseDirdIntegrationTest): asset = 'personal_only' def test_that_import_with_cp1252_chars_is_valid(self): - csv = textwrap.dedent('''\ + csv = textwrap.dedent( + '''\ firstname,lastname valérie,vidalzami - ''').encode('cp1252') + ''' + ).encode('cp1252') result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT, encoding='cp1252') - assert_that(result['created'], contains_inanyorder( - has_entries({'firstname': 'valérie', 'lastname': 'vidalzami'}))) + assert_that( + result['created'], + contains_inanyorder( + has_entries({'firstname': 'valérie', 'lastname': 'vidalzami'}) + ), + ) diff --git a/integration_tests/suite/test_phone.py b/integration_tests/suite/test_phone.py index 0a02d6b0..4f0cd481 100644 --- a/integration_tests/suite/test_phone.py +++ b/integration_tests/suite/test_phone.py @@ -2,17 +2,11 @@ # SPDX-License-Identifier: GPL-3.0-or-later from xml.dom.minidom import parseString as parse_xml -from hamcrest import ( - assert_that, - equal_to, -) +from hamcrest import assert_that, equal_to from .helpers.base import BaseDirdIntegrationTest from .helpers.config import new_phone_config -from .helpers.constants import ( - VALID_TOKEN_MAIN_TENANT, - VALID_UUID, -) +from .helpers.constants import VALID_TOKEN_MAIN_TENANT, VALID_UUID class TestPhone(BaseDirdIntegrationTest): @@ -22,7 +16,7 @@ class TestPhone(BaseDirdIntegrationTest): def test_no_fallback_no_multiple_results(self): xml_content = self.get_lookup_cisco( - 'test_fallback', VALID_UUID, term='Ali', token=VALID_TOKEN_MAIN_TENANT, + 'test_fallback', VALID_UUID, term='Ali', token=VALID_TOKEN_MAIN_TENANT ) results = self._get_directory_entries(xml_content) @@ -31,7 +25,7 @@ def test_no_fallback_no_multiple_results(self): def test_no_results(self): xml_content = self.get_lookup_cisco( - 'test_fallback', VALID_UUID, term='Dia', token=VALID_TOKEN_MAIN_TENANT, + 'test_fallback', VALID_UUID, term='Dia', token=VALID_TOKEN_MAIN_TENANT ) results = self._get_directory_entries(xml_content) @@ -40,7 +34,7 @@ def test_no_results(self): def test_results_are_sorted(self): xml_content = self.get_lookup_cisco( - 'test_sorted', VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, + 'test_sorted', VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT ) results = self._get_directory_entries(xml_content) @@ -52,7 +46,9 @@ def _get_directory_entries(self, xml_string): results = [] for directory_entry in document.getElementsByTagName('DirectoryEntry'): name = self._get_text(directory_entry.getElementsByTagName('Name')[0]) - number = self._get_text(directory_entry.getElementsByTagName('Telephone')[0]) + number = self._get_text( + directory_entry.getElementsByTagName('Telephone')[0] + ) results.append((name, number)) return results diff --git a/integration_tests/suite/test_phone_view.py b/integration_tests/suite/test_phone_view.py index 1532593f..51f6adba 100644 --- a/integration_tests/suite/test_phone_view.py +++ b/integration_tests/suite/test_phone_view.py @@ -3,18 +3,9 @@ from .helpers.base import BaseDirdIntegrationTest from .helpers.config import new_phone_view_config -from .helpers.constants import ( - VALID_TOKEN_MAIN_TENANT, - VALID_UUID, -) - -from hamcrest import ( - assert_that, - contains_string, - equal_to, - matches_regexp, - not_, -) +from .helpers.constants import VALID_TOKEN_MAIN_TENANT, VALID_UUID + +from hamcrest import assert_that, contains_string, equal_to, matches_regexp, not_ URL_REGEX = '.*.*{}.*.*' TAG_REGEX = '.*<{tag}>.*' @@ -28,7 +19,7 @@ class TestPhoneView(BaseDirdIntegrationTest): def test_given_invalid_offset_then_lookup_return_400(self): result = self.get_lookup_cisco_result( - self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, offset=-1, + self.profile, VALID_UUID, term='A', token=VALID_TOKEN_MAIN_TENANT, offset=-1 ) assert_that(result.status_code, equal_to((400))) @@ -45,7 +36,9 @@ def test_that_dird_replace_url_by_proxy(self): assert_that(result, matches_regexp(URL_REGEX.format(proxy_url))) def test_that_menu_return_input_url_when_no_proxy(self): - result = self.get_menu_cisco(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_menu_cisco( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT + ) assert_that(result, matches_regexp(URL_REGEX.format('/input'))) assert_that(result, not_(matches_regexp(URL_REGEX.format('/menu')))) @@ -63,20 +56,26 @@ def test_that_input_replace_url_by_proxy(self): assert_that(result, matches_regexp(URL_REGEX.format(proxy_url))) def test_that_input_return_lookup_url_when_no_proxy(self): - result = self.get_input_cisco(self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_cisco( + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT + ) assert_that(result, matches_regexp(URL_REGEX.format('/lookup'))) assert_that(result, not_(matches_regexp(URL_REGEX.format('/input')))) def test_that_input_return_lookup_url_when_profile_name_input(self): profile = 'input' - result = self.get_input_cisco(profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT) + result = self.get_input_cisco( + profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT + ) assert_that(result, matches_regexp(URL_REGEX.format('/lookup/input'))) def test_that_lookup_replace_url_by_proxy_when_paging(self): proxy_url = 'http://my-proxy.com/lookup' - result = self.get_lookup_cisco(self.profile, VALID_UUID, term='user', proxy=proxy_url) + result = self.get_lookup_cisco( + self.profile, VALID_UUID, term='user', proxy=proxy_url + ) assert_that(result, matches_regexp(URL_REGEX.format(proxy_url))) @@ -88,7 +87,9 @@ def test_that_lookup_return_lookup_url_when_no_proxy_and_paging(self): def test_that_lookup_return_lookup_template(self): result = self.get_lookup_cisco(self.profile, VALID_UUID, term='toto') - assert_that(result, matches_regexp(TAG_REGEX.format(tag='CiscoIPPhoneDirectory'))) + assert_that( + result, matches_regexp(TAG_REGEX.format(tag='CiscoIPPhoneDirectory')) + ) def test_that_lookup_return_result(self): result = self.get_lookup_cisco(self.profile, VALID_UUID, term='Alice') @@ -98,92 +99,92 @@ def test_that_lookup_return_result(self): def test_that_lookup_return_400_when_no_term(self): result = self.get_lookup_cisco_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to(400)) def test_that_lookup_return_404_when_unknown_profile(self): result = self.get_lookup_cisco_result( - 'quiproquo', VALID_UUID, term='alice', token=VALID_TOKEN_MAIN_TENANT, + 'quiproquo', VALID_UUID, term='alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to(404)) def test_aastra_input_route(self): result = self.get_input_aastra_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_aastra_lookup_route(self): result = self.get_lookup_aastra_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_cisco_input_route(self): result = self.get_input_cisco_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_cisco_menu_route(self): result = self.get_menu_cisco_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_cisco_lookup_route(self): result = self.get_lookup_cisco_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_polycom_input_route(self): result = self.get_input_polycom_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_polycom_lookup_route(self): result = self.get_lookup_polycom_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_snom_input_route(self): result = self.get_input_snom_result( - self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_snom_lookup_route(self): result = self.get_lookup_snom_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_thomson_lookup_route(self): result = self.get_lookup_thomson_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_yealink_lookup_route(self): result = self.get_lookup_yealink_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_gigaset_lookup_route(self): result = self.get_lookup_gigaset_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) def test_htek_lookup_route(self): result = self.get_lookup_htek_result( - self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT, + self.profile, VALID_UUID, term='Alice', token=VALID_TOKEN_MAIN_TENANT ) assert_that(result.status_code, equal_to((200))) diff --git a/integration_tests/suite/test_phonebook.py b/integration_tests/suite/test_phonebook.py index acaf4fb0..7a23338a 100644 --- a/integration_tests/suite/test_phonebook.py +++ b/integration_tests/suite/test_phonebook.py @@ -2,18 +2,11 @@ # SPDX-License-Identifier: GPL-3.0-or-later from mock import ANY -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - equal_to, - has_entries, -) +from hamcrest import assert_that, contains, contains_inanyorder, equal_to, has_entries from .helpers.base import BasePhonebookTestCase class TestList(BasePhonebookTestCase): - def test_unknown_tenant(self): self.set_tenants('invalid') valid_body = {'name': 'foobar'} @@ -31,12 +24,7 @@ def test_valid(self): result = self.list_phonebooks('valid') assert_that( result.json(), - has_entries( - items=contains_inanyorder( - has_entries(**phonebook_1), - ), - total=1, - ) + has_entries(items=contains_inanyorder(has_entries(**phonebook_1)), total=1), ) def test_pagination(self): @@ -57,7 +45,7 @@ def assert_matches(result, *phonebooks): *[has_entries(**phonebook) for phonebook in phonebooks] ), total=3, - ) + ), ) result = self.list_phonebooks('pagination', order='name', direction='asc') @@ -98,7 +86,6 @@ def assert_matches(result, *phonebooks): class TestPost(BasePhonebookTestCase): - def test_unknown_tenant(self): self.set_tenants() valid_body = {'name': 'foobar'} @@ -110,14 +97,7 @@ def test_valid(self): valid_body = {'name': 'foobar'} result = self.post_phonebook('valid', valid_body) assert_that(result.status_code, equal_to(201)) - assert_that( - result.json(), - has_entries( - id=ANY, - name='foobar', - description=None, - ) - ) + assert_that(result.json(), has_entries(id=ANY, name='foobar', description=None)) result = self.post_phonebook('valid', valid_body) assert_that(result.status_code, equal_to(409)) @@ -143,7 +123,6 @@ def test_invalid_bodies(self): class TestGet(BasePhonebookTestCase): - def test_unknown_tenant(self): self.set_tenants('valid') valid_body = {'name': 'foobar'} @@ -178,7 +157,6 @@ def test_unknown_phonebook(self): class TestDelete(BasePhonebookTestCase): - def test_unknown_tenant(self): self.set_tenants('invalid') valid_body = {'name': 'foobar'} @@ -213,7 +191,6 @@ def test_unknown_phonebook(self): class TestPut(BasePhonebookTestCase): - def test_unknown_tenant(self): self.set_tenants('invalid') valid_body = {'name': 'foobar'} @@ -273,12 +250,13 @@ def test_duplicated(self): valid_body = {'name': 'duplicate me NOT'} phonebook = self.post_phonebook('invalid', valid_body).json() - result = self.put_phonebook('invalid', phonebook['id'], {'name': 'duplicate me'}) + result = self.put_phonebook( + 'invalid', phonebook['id'], {'name': 'duplicate me'} + ) assert_that(result.status_code, equal_to(409)) class _BasePhonebookContactTestCase(BasePhonebookTestCase): - def setUp(self): super().setUp() self.tenant_1 = 'valid' @@ -299,14 +277,11 @@ def tearDown(self): class TestContactDelete(_BasePhonebookContactTestCase): - def setUp(self): super().setUp() self.set_tenants(self.tenant_1) self.contact = self.post_phonebook_contact( - self.tenant_1, - self.phonebook_1['id'], - {'firstname': 'Alice'}, + self.tenant_1, self.phonebook_1['id'], {'firstname': 'Alice'} ).json() self.contact_id = self.contact['id'] @@ -336,14 +311,11 @@ def _delete(self, tenant, phonebook_id, contact_id): class TestContactGet(_BasePhonebookContactTestCase): - def setUp(self): super().setUp() self.set_tenants(self.tenant_1) self.contact = self.post_phonebook_contact( - self.tenant_1, - self.phonebook_1['id'], - {'firstname': 'Alice'}, + self.tenant_1, self.phonebook_1['id'], {'firstname': 'Alice'} ).json() self.contact_id = self.contact['id'] @@ -359,7 +331,9 @@ def test_unknown_tenant_phonebook_or_contact(self): res = self._get(self.tenant_1, self.phonebook_2['id'], self.contact_id) assert_that(res.status_code, equal_to(404), 'unknown phonebook') - self.delete_phonebook_contact(self.tenant_1, self.phonebook_1['id'], self.contact_id) + self.delete_phonebook_contact( + self.tenant_1, self.phonebook_1['id'], self.contact_id + ) res = self._get(self.tenant_1, self.phonebook_1['id'], self.contact_id) assert_that(res.status_code, equal_to(404), 'unknown contact') @@ -373,7 +347,6 @@ def _get(self, tenant, phonebook_id, contact_id): class TestContactList(_BasePhonebookContactTestCase): - def test_unknown_tenant_or_phonebook(self): self.set_tenants(self.tenant_2) result = self.list_phonebook_contacts(self.tenant_2, self.phonebook_1['id']) @@ -397,17 +370,17 @@ def assert_matches(result, *contacts): assert_that( result.json(), has_entries( - items=contains( - *[has_entries(**contact) for contact in contacts] - ), + items=contains(*[has_entries(**contact) for contact in contacts]), total=3, - ) + ), ) result = self.list_phonebook_contacts(*args, order='firstname', direction='asc') assert_matches(result, contact_1, contact_2, contact_3) - result = self.list_phonebook_contacts(*args, order='firstname', direction='desc') + result = self.list_phonebook_contacts( + *args, order='firstname', direction='desc' + ) assert_matches(result, contact_3, contact_2, contact_1) result = self.list_phonebook_contacts(*args, order='lastname') @@ -419,7 +392,9 @@ def assert_matches(result, *contacts): result = self.list_phonebook_contacts(*args, order='firstname', offset=1) assert_matches(result, contact_2, contact_3) - result = self.list_phonebook_contacts(*args, order='firstname', limit=1, offset=1) + result = self.list_phonebook_contacts( + *args, order='firstname', limit=1, offset=1 + ) assert_matches(result, contact_2) invalid_limit_offset = [-1, True, False, 'foobar', 3.14] @@ -437,15 +412,18 @@ def assert_matches(result, *contacts): class TestContactPost(_BasePhonebookContactTestCase): - def test_unknown_tenant_or_phonebook(self): body = {'firstname': 'Alice'} self.set_tenants(self.tenant_2) - result = self.post_phonebook_contact(self.tenant_2, self.phonebook_1['id'], body) + result = self.post_phonebook_contact( + self.tenant_2, self.phonebook_1['id'], body + ) assert_that(result.status_code, equal_to(404)) - result = self.post_phonebook_contact(self.tenant_1, self.phonebook_1['id'], body) + result = self.post_phonebook_contact( + self.tenant_1, self.phonebook_1['id'], body + ) assert_that(result.status_code, equal_to(404)) def test_duplicates(self): @@ -453,23 +431,24 @@ def test_duplicates(self): self.set_tenants(self.tenant_1) self.post_phonebook_contact(self.tenant_1, self.phonebook_1['id'], body) - result = self.post_phonebook_contact(self.tenant_1, self.phonebook_1['id'], body) + result = self.post_phonebook_contact( + self.tenant_1, self.phonebook_1['id'], body + ) assert_that(result.status_code, equal_to(409)) self.set_tenants(self.tenant_2) - result = self.post_phonebook_contact(self.tenant_2, self.phonebook_2['id'], body) + result = self.post_phonebook_contact( + self.tenant_2, self.phonebook_2['id'], body + ) assert_that(result.status_code, equal_to(201)) class TestContactPut(_BasePhonebookContactTestCase): - def setUp(self): super().setUp() self.set_tenants(self.tenant_1) self.contact = self.post_phonebook_contact( - self.tenant_1, - self.phonebook_1['id'], - {'firstname': 'Alice'}, + self.tenant_1, self.phonebook_1['id'], {'firstname': 'Alice'} ).json() self.contact_id = self.contact['id'] @@ -487,7 +466,9 @@ def test_unknown_tenant_phonebook_or_contact(self): res = self._put(self.tenant_1, self.phonebook_2['id'], self.contact_id, body) assert_that(res.status_code, equal_to(404), 'unknown phonebook') - self.delete_phonebook_contact(self.tenant_1, self.phonebook_1['id'], self.contact_id) + self.delete_phonebook_contact( + self.tenant_1, self.phonebook_1['id'], self.contact_id + ) res = self._put(self.tenant_1, self.phonebook_1['id'], self.contact_id, body) assert_that(res.status_code, equal_to(404), 'unknown contact') @@ -503,7 +484,6 @@ def _put(self, tenant, phonebook_id, contact_id, body): class TestContactImport(_BasePhonebookContactTestCase): - def setUp(self): super().setUp() self.body = '''\ @@ -532,7 +512,7 @@ def test_post(self): has_entries(firstname='Bob', lastname='B'), ), total=2, - ) + ), ) def import_(self, tenant, phonebook_id, body): diff --git a/integration_tests/suite/test_phonebook_http.py b/integration_tests/suite/test_phonebook_http.py index 08b6a3c4..d96aac75 100644 --- a/integration_tests/suite/test_phonebook_http.py +++ b/integration_tests/suite/test_phonebook_http.py @@ -31,9 +31,7 @@ class BasePhonebookCRUDTestCase(BaseDirdIntegrationTest): asset = 'all_routes' - valid_body = { - 'name': 'main', - } + valid_body = {'name': 'main'} def assert_unknown_source_exception(self, source_uuid, exception): assert_that(exception.response.status_code, equal_to(404)) @@ -43,7 +41,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) @contextmanager @@ -56,7 +54,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BasePhonebookCRUDTestCase): - @fixtures.phonebook_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -66,7 +63,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.phonebook_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -96,46 +95,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BasePhonebookCRUDTestCase): - @fixtures.phonebook_source(name='abc') @fixtures.phonebook_source(name='bcd') @fixtures.phonebook_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.phonebook_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.phonebook_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.phonebook_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.phonebook_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.phonebook_source(name='abc') @@ -144,38 +125,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.phonebook_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.phonebook_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.phonebook_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.phonebook_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.phonebook_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -187,54 +152,33 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.phonebook_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.phonebook_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.phonebook_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.phonebook_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BasePhonebookCRUDTestCase): - def test_post(self): try: self.client.phonebook_source.create({}) except Exception as e: assert_that(e.response.status_code, equal_to(400)) assert_that( - e.response.json(), - has_entries( - message=ANY, - error_id='invalid-data', - ), + e.response.json(), has_entries(message=ANY, error_id='invalid-data') ) else: self.fail('Should have raised') @@ -242,9 +186,9 @@ def test_post(self): with self.source(self.client, self.valid_body): assert_that( calling(self.client.phonebook_source.create).with_args(self.valid_body), - raises(Exception).matching(has_properties( - response=has_properties(status_code=409), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -254,37 +198,40 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.phonebook_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.phonebook_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.phonebook_source.create).with_args(self.valid_body), + calling(sub_tenant_client.phonebook_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BasePhonebookCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { 'name': 'new', 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.phonebook_source(name='foobar') @@ -292,12 +239,18 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.phonebook_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( - calling(self.client.phonebook_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + calling(self.client.phonebook_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -305,17 +258,15 @@ def test_put(self, foobar, other): except Exception as e: assert_that(e.response.status_code, equal_to(400)) assert_that( - e.response.json(), - has_entries( - message=ANY, - error_id='invalid-data', - ), + e.response.json(), has_entries(message=ANY, error_id='invalid-data') ) else: self.fail('Should have raised') assert_that( - calling(self.client.phonebook_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.phonebook_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -329,7 +280,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.phonebook_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -339,10 +290,14 @@ def test_put_multi_tenant(self, sub, main): sub_tenant_client = self.get_client(VALID_TOKEN_SUB_TENANT) assert_that( - calling(sub_tenant_client.phonebook_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + calling(sub_tenant_client.phonebook_source.edit).with_args( + main['uuid'], sub + ), + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -354,14 +309,13 @@ def test_put_multi_tenant(self, sub, main): assert_that( calling(main_tenant_client.phonebook_source.edit).with_args( - sub['uuid'], self.new_body, + sub['uuid'], self.new_body ), not_(raises(Exception)), ) class TestGet(BasePhonebookCRUDTestCase): - @fixtures.phonebook_source(name='foobar') def test_get(self, wazo): response = self.client.phonebook_source.get(wazo['uuid']) diff --git a/integration_tests/suite/test_profiles.py b/integration_tests/suite/test_profiles.py index 72e31c37..5fe2e275 100644 --- a/integration_tests/suite/test_profiles.py +++ b/integration_tests/suite/test_profiles.py @@ -50,7 +50,6 @@ def profile(self, client, *args, **kwargs): class TestDelete(BaseProfileTestCase): - @fixtures.display() @fixtures.csv_source() def test_delete(self, source, display): @@ -68,7 +67,7 @@ def test_delete(self, source, display): assert_that( calling(self.client.profiles.delete).with_args(profile['uuid']), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) @@ -89,25 +88,25 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): assert_that( calling(sub_tenant_client.profiles.delete).with_args(profile['uuid']), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( calling(sub_tenant_client.profiles.delete).with_args( - profile['uuid'], tenant_uuid=MAIN_TENANT, + profile['uuid'], tenant_uuid=MAIN_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=401)), + has_properties(response=has_properties(status_code=401)) ), ) assert_that( calling(main_tenant_client.profiles.delete).with_args( - profile['uuid'], tenant_uuid=SUB_TENANT, + profile['uuid'], tenant_uuid=SUB_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) @@ -124,7 +123,6 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): class TestGet(BaseProfileTestCase): - @fixtures.display() @fixtures.csv_source() def test_get(self, source, display): @@ -139,7 +137,9 @@ def test_get(self, source, display): assert_that( calling(self.client.profiles.get).with_args(UNKNOWN_UUID), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) @fixtures.display(token=VALID_TOKEN_MAIN_TENANT) @@ -159,25 +159,25 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): assert_that( calling(sub_tenant_client.profiles.get).with_args(profile['uuid']), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( calling(main_tenant_client.profiles.get).with_args( - profile['uuid'], tenant_uuid=SUB_TENANT, + profile['uuid'], tenant_uuid=SUB_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( calling(sub_tenant_client.profiles.get).with_args( - profile['uuid'], tenant_uuid=MAIN_TENANT, + profile['uuid'], tenant_uuid=MAIN_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=401)), + has_properties(response=has_properties(status_code=401)) ), ) @@ -192,7 +192,6 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): class TestList(BaseProfileTestCase): - @fixtures.display() @fixtures.csv_source() def test_search(self, source, display): @@ -201,12 +200,12 @@ def test_search(self, source, display): body_bcd = dict(name='bcd', **base_body) body_cde = dict(name='cde', **base_body) - with self.profile(self.client, body_abc) as abc, \ - self.profile(self.client, body_bcd) as bcd, \ - self.profile(self.client, body_cde) as cde: + with self.profile(self.client, body_abc) as abc, self.profile( + self.client, body_bcd + ) as bcd, self.profile(self.client, body_cde) as cde: result = self.client.profiles.list() self.assert_list_result( - result, contains_inanyorder(abc, bcd, cde), total=3, filtered=3, + result, contains_inanyorder(abc, bcd, cde), total=3, filtered=3 ) result = self.client.profiles.list(name='abc') @@ -216,7 +215,9 @@ def test_search(self, source, display): self.assert_list_result(result, contains(cde), total=3, filtered=1) result = self.client.profiles.list(search='b') - self.assert_list_result(result, contains_inanyorder(abc, bcd), total=3, filtered=2) + self.assert_list_result( + result, contains_inanyorder(abc, bcd), total=3, filtered=2 + ) @fixtures.display() @fixtures.csv_source() @@ -226,14 +227,18 @@ def test_pagination(self, source, display): body_bcd = dict(name='bcd', **base_body) body_cde = dict(name='cde', **base_body) - with self.profile(self.client, body_abc) as abc, \ - self.profile(self.client, body_bcd) as bcd, \ - self.profile(self.client, body_cde) as cde: + with self.profile(self.client, body_abc) as abc, self.profile( + self.client, body_bcd + ) as bcd, self.profile(self.client, body_cde) as cde: result = self.client.profiles.list(order='name') - self.assert_list_result(result, contains(abc, bcd, cde), total=3, filtered=3) + self.assert_list_result( + result, contains(abc, bcd, cde), total=3, filtered=3 + ) result = self.client.profiles.list(order='name', direction='desc') - self.assert_list_result(result, contains(cde, bcd, abc), total=3, filtered=3) + self.assert_list_result( + result, contains(cde, bcd, abc), total=3, filtered=3 + ) result = self.client.profiles.list(order='name', limit=2) self.assert_list_result(result, contains(abc, bcd), total=3, filtered=3) @@ -260,33 +265,45 @@ def test_multi_tenant(self, sub_source, main_source, sub_display, main_display): 'services': {'lookup': {'sources': [sub_source]}}, } - with self.profile(main_tenant_client, body_main_profile) as main, \ - self.profile(sub_tenant_client, body_sub_profile) as sub: + with self.profile(main_tenant_client, body_main_profile) as main, self.profile( + sub_tenant_client, body_sub_profile + ) as sub: result = main_tenant_client.profiles.list() self.assert_list_result(result, contains(main), total=1, filtered=1) result = main_tenant_client.profiles.list(recurse=True) - self.assert_list_result(result, contains_inanyorder(main, sub), total=2, filtered=2) + self.assert_list_result( + result, contains_inanyorder(main, sub), total=2, filtered=2 + ) result = sub_tenant_client.profiles.list() - self.assert_list_result(result, contains_inanyorder(sub), total=1, filtered=1) + self.assert_list_result( + result, contains_inanyorder(sub), total=1, filtered=1 + ) result = sub_tenant_client.profiles.list(recurse=True) - self.assert_list_result(result, contains_inanyorder(sub), total=1, filtered=1) + self.assert_list_result( + result, contains_inanyorder(sub), total=1, filtered=1 + ) - result = main_tenant_client.profiles.list(tenant_uuid=SUB_TENANT, recurse=True) - self.assert_list_result(result, contains_inanyorder(sub), total=1, filtered=1) + result = main_tenant_client.profiles.list( + tenant_uuid=SUB_TENANT, recurse=True + ) + self.assert_list_result( + result, contains_inanyorder(sub), total=1, filtered=1 + ) assert_that( - calling(sub_tenant_client.profiles.list).with_args(tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties( - response=has_properties(status_code=401), - )) + calling(sub_tenant_client.profiles.list).with_args( + tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) class TestPost(BaseProfileTestCase): - @fixtures.display() def test_invalid_bodies(self, display): invalid_bodies = [ @@ -313,7 +330,7 @@ def test_duplicate(self, source, display): assert_that( calling(self.client.profiles.create).with_args(body), raises(Exception).matching( - has_properties(response=has_properties(status_code=409)), + has_properties(response=has_properties(status_code=409)) ), ) @@ -358,28 +375,37 @@ def test_all_fields(self, source, display): 'name': 'profile', 'display': {'uuid': display['uuid']}, 'services': { - 'lookup': {'sources': [{'uuid': source['uuid']}], 'options': {'timeout': 5}}, - 'reverse': {'sources': [{'uuid': source['uuid']}], 'options': {'timeout': 0.5}}, + 'lookup': { + 'sources': [{'uuid': source['uuid']}], + 'options': {'timeout': 5}, + }, + 'reverse': { + 'sources': [{'uuid': source['uuid']}], + 'options': {'timeout': 0.5}, + }, }, } with self.profile(self.client, body) as profile: - assert_that(profile, has_entries( - uuid=uuid_(), - tenant_uuid=MAIN_TENANT, - name='profile', - display=has_entries(uuid=display['uuid']), - services=has_entries( - lookup=has_entries( - sources=contains(has_entries(uuid=source['uuid'])), - options=has_entries(timeout=5) - ), - reverse=has_entries( - sources=contains(has_entries(uuid=source['uuid'])), - options=has_entries(timeout=0.5) + assert_that( + profile, + has_entries( + uuid=uuid_(), + tenant_uuid=MAIN_TENANT, + name='profile', + display=has_entries(uuid=display['uuid']), + services=has_entries( + lookup=has_entries( + sources=contains(has_entries(uuid=source['uuid'])), + options=has_entries(timeout=5), + ), + reverse=has_entries( + sources=contains(has_entries(uuid=source['uuid'])), + options=has_entries(timeout=0.5), + ), ), ), - )) + ) @fixtures.csv_source(token=VALID_TOKEN_MAIN_TENANT) @fixtures.csv_source(token=VALID_TOKEN_SUB_TENANT) @@ -396,8 +422,12 @@ def test_multi_tenant(self, sub_display, main_display, sub_source, main_source): } assert_that( - calling(sub_tenant_client.profiles.create).with_args(body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.profiles.create).with_args( + body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) body = { @@ -419,7 +449,6 @@ def assert_invalid_body(self, body): class TestPut(BaseProfileTestCase): - @fixtures.display() @fixtures.display() @fixtures.csv_source() @@ -437,47 +466,50 @@ def test_put(self, s2, s1, d2, d1): 'services': { 'reverse': {'sources': [s1, s2]}, 'favorites': {'sources': [s2]}, - } + }, } self.client.profiles.edit(profile['uuid'], new_body) - assert_that(self.client.profiles.get(profile['uuid']), has_entries( - uuid=profile['uuid'], - name='updated', - services=has_entries( - reverse=has_entries( - sources=contains( - has_entries(uuid=s1['uuid']), - has_entries(uuid=s2['uuid']), + assert_that( + self.client.profiles.get(profile['uuid']), + has_entries( + uuid=profile['uuid'], + name='updated', + services=has_entries( + reverse=has_entries( + sources=contains( + has_entries(uuid=s1['uuid']), + has_entries(uuid=s2['uuid']), + ) ), - ), - favorites=has_entries( - sources=contains( - has_entries(uuid=s2['uuid']), + favorites=has_entries( + sources=contains(has_entries(uuid=s2['uuid'])) ), ), ), - )) + ) assert_that( calling(self.client.profiles.edit).with_args(UNKNOWN_UUID, new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) @fixtures.display() @fixtures.csv_source() def test_duplicate(self, s1, d1): - body = { - 'display': d1, - 'services': {'lookup': {'sources': [s1]}}, - } + body = {'display': d1, 'services': {'lookup': {'sources': [s1]}}} - with self.profile(self.client, dict(name='a', **body)), \ - self.profile(self.client, dict(name='b', **body)) as b: + with self.profile(self.client, dict(name='a', **body)), self.profile( + self.client, dict(name='b', **body) + ) as b: assert_that( - calling(self.client.profiles.edit).with_args(b['uuid'], dict(name='a', **body)), + calling(self.client.profiles.edit).with_args( + b['uuid'], dict(name='a', **body) + ), raises(Exception).matching( - has_properties(response=has_properties(status_code=409)), + has_properties(response=has_properties(status_code=409)) ), ) @@ -496,27 +528,29 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): } with self.profile(main_tenant_client, body) as profile: assert_that( - calling(sub_tenant_client.profiles.edit).with_args(profile['uuid'], body), + calling(sub_tenant_client.profiles.edit).with_args( + profile['uuid'], body + ), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( calling(main_tenant_client.profiles.edit).with_args( - profile['uuid'], body, tenant_uuid=SUB_TENANT, + profile['uuid'], body, tenant_uuid=SUB_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( calling(sub_tenant_client.profiles.edit).with_args( - profile['uuid'], body, tenant_uuid=MAIN_TENANT, + profile['uuid'], body, tenant_uuid=MAIN_TENANT ), raises(Exception).matching( - has_properties(response=has_properties(status_code=401)), + has_properties(response=has_properties(status_code=401)) ), ) @@ -528,15 +562,20 @@ def test_multi_tenant(self, sub_source, sub_display, main_source, main_display): with self.profile(sub_tenant_client, body) as profile: main_tenant_client.profiles.edit(profile['uuid'], body) result = main_tenant_client.profiles.get(profile['uuid']) - assert_that(result, has_entries( - uuid=profile['uuid'], - tenant_uuid=profile['tenant_uuid'], - display=has_entries(uuid=sub_display['uuid']), - name='profile', - services=has_entries( - lookup=has_entries(sources=contains(has_entries(uuid=sub_source['uuid']))), - ) - )) + assert_that( + result, + has_entries( + uuid=profile['uuid'], + tenant_uuid=profile['tenant_uuid'], + display=has_entries(uuid=sub_display['uuid']), + name='profile', + services=has_entries( + lookup=has_entries( + sources=contains(has_entries(uuid=sub_source['uuid'])) + ) + ), + ), + ) @fixtures.display(token=VALID_TOKEN_MAIN_TENANT) @fixtures.display(token=VALID_TOKEN_SUB_TENANT) @@ -553,9 +592,11 @@ def test_unknown_display(self, source, sub_display, main_display): new_body = dict(body) new_body['display'] = {'uuid': display_uuid} assert_that( - calling(self.client.profiles.edit).with_args(profile['uuid'], new_body), + calling(self.client.profiles.edit).with_args( + profile['uuid'], new_body + ), raises(Exception).matching( - has_properties(response=has_properties(status_code=400)), + has_properties(response=has_properties(status_code=400)) ), ) @@ -574,9 +615,11 @@ def test_unknown_source(self, sub_source, main_source, display): new_body = dict(body) new_body['services']['lookup']['sources'] = [{'uuid': source_uuid}] assert_that( - calling(self.client.profiles.edit).with_args(profile['uuid'], new_body), + calling(self.client.profiles.edit).with_args( + profile['uuid'], new_body + ), raises(Exception).matching( - has_properties(response=has_properties(status_code=400)), + has_properties(response=has_properties(status_code=400)) ), ) @@ -588,51 +631,60 @@ class TestGetSourcesFromProfile(BaseProfileTestCase): def test_when_get_then_sources_returned(self): response = self.client.directories.list_sources('main') - assert_that(response['items'], contains_inanyorder( - has_entries(name='a_wazo_main', backend='wazo'), - has_entries(name='personal_main', backend='personal'), - has_entries(name='csv_main', backend='csv'), - )) + assert_that( + response['items'], + contains_inanyorder( + has_entries(name='a_wazo_main', backend='wazo'), + has_entries(name='personal_main', backend='personal'), + has_entries(name='csv_main', backend='csv'), + ), + ) def test_that_now_all_source_info_is_returned(self): response = self.client.directories.list_sources('main') - assert_that(response['items'][0], contains_inanyorder( - 'uuid', - 'tenant_uuid', - 'name', - 'backend', - )) + assert_that( + response['items'][0], + contains_inanyorder('uuid', 'tenant_uuid', 'name', 'backend'), + ) def test_given_asc_direction_when_get_then_sources_returned(self): list_params = {'direction': 'asc'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='a_wazo_main'), - has_entries(name='csv_main'), - has_entries(name='personal_main'), - )) + assert_that( + response['items'], + contains( + has_entries(name='a_wazo_main'), + has_entries(name='csv_main'), + has_entries(name='personal_main'), + ), + ) def test_given_desc_direction_when_get_then_sources_returned(self): list_params = {'direction': 'desc'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='personal_main', backend='personal'), - has_entries(name='csv_main', backend='csv'), - has_entries(name='a_wazo_main', backend='wazo'), - )) + assert_that( + response['items'], + contains( + has_entries(name='personal_main', backend='personal'), + has_entries(name='csv_main', backend='csv'), + has_entries(name='a_wazo_main', backend='wazo'), + ), + ) def test_given_random_direction_when_get_then_bad_request(self): list_params = {'direction': '42'} assert_that( - calling(self.client.directories.list_sources).with_args('main', **list_params), + calling(self.client.directories.list_sources).with_args( + 'main', **list_params + ), raises(HTTPError).matching( - has_properties(response=has_properties(status_code=400)), + has_properties(response=has_properties(status_code=400)) ), ) @@ -641,45 +693,55 @@ def test_given_name_order_when_get_then_sources_returned(self): response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='a_wazo_main', backend='wazo'), - has_entries(name='csv_main', backend='csv'), - has_entries(name='personal_main', backend='personal'), - )) + assert_that( + response['items'], + contains( + has_entries(name='a_wazo_main', backend='wazo'), + has_entries(name='csv_main', backend='csv'), + has_entries(name='personal_main', backend='personal'), + ), + ) def test_given_backend_order_when_get_then_sources_returned(self): list_params = {'order': 'backend'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='csv_main', backend='csv'), - has_entries(name='personal_main', backend='personal'), - has_entries(name='a_wazo_main', backend='wazo'), - )) + assert_that( + response['items'], + contains( + has_entries(name='csv_main', backend='csv'), + has_entries(name='personal_main', backend='personal'), + has_entries(name='a_wazo_main', backend='wazo'), + ), + ) def test_given_random_order_when_get_then_bad_request(self): list_params = {'order': '42'} assert_that( - calling(self.client.directories.list_sources).with_args('main', **list_params), + calling(self.client.directories.list_sources).with_args( + 'main', **list_params + ), raises(HTTPError).matching( - has_properties(response=has_properties(status_code=400)), + has_properties(response=has_properties(status_code=400)) ), ) def test_given_wrong_tenant_when_get_then_not_found(self): assert_that( calling(self.client.directories.list_sources).with_args( - 'main', tenant_uuid=SUB_TENANT, + 'main', tenant_uuid=SUB_TENANT ), raises(HTTPError).matching( - has_properties(response=has_properties(status_code=404)), + has_properties(response=has_properties(status_code=404)) ), ) assert_that( - calling(self.client.directories.list_sources).with_args('sub', tenant_uuid=SUB_TENANT), + calling(self.client.directories.list_sources).with_args( + 'sub', tenant_uuid=SUB_TENANT + ), not_(raises(Exception)), ) @@ -688,10 +750,10 @@ def test_given_sub_tenant_when_get_main_tenant_then_unauthorized(self): assert_that( calling(sub_tenant_client.directories.list_sources).with_args( - 'main', tenant_uuid=MAIN_TENANT, + 'main', tenant_uuid=MAIN_TENANT ), raises(HTTPError).matching( - has_properties(response=has_properties(status_code=401)), + has_properties(response=has_properties(status_code=401)) ), ) @@ -700,76 +762,84 @@ def test_given_limit_when_get_then_sources_returned(self): response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='a_wazo_main', backend='wazo'), - )) + assert_that( + response['items'], contains(has_entries(name='a_wazo_main', backend='wazo')) + ) def test_given_over_limit_when_get_then_sources_returned(self): list_params = {'limit': '42'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='a_wazo_main', backend='wazo'), - has_entries(name='csv_main', backend='csv'), - has_entries(name='personal_main', backend='personal'), - )) + assert_that( + response['items'], + contains( + has_entries(name='a_wazo_main', backend='wazo'), + has_entries(name='csv_main', backend='csv'), + has_entries(name='personal_main', backend='personal'), + ), + ) def test_given_offset_when_get_then_sources_returned(self): list_params = {'offset': '2'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response['items'], contains( - has_entries(name='personal_main', backend='personal'), - )) + assert_that( + response['items'], + contains(has_entries(name='personal_main', backend='personal')), + ) def test_given_oversized_offset_when_get_then_no_sources_returned(self): list_params = {'offset': '42'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response, has_entries( - total=3, - filtered=3, - items=empty(), - )) + assert_that(response, has_entries(total=3, filtered=3, items=empty())) def test_given_order_offset_limit_when_get_then_sources_returned(self): - list_params = { - 'limit': '1', - 'offset': '1', - 'order': 'backend', - } + list_params = {'limit': '1', 'offset': '1', 'order': 'backend'} response = self.client.directories.list_sources('main', **list_params) - assert_that(response, has_entries( - items=contains(has_entries(name='personal_main', backend='personal')), - total=3, - filtered=3, - )) + assert_that( + response, + has_entries( + items=contains(has_entries(name='personal_main', backend='personal')), + total=3, + filtered=3, + ), + ) def test_searches(self): response = self.client.directories.list_sources('main', name='personal_main') - assert_that(response, has_entries( - total=3, - filtered=1, - items=contains(has_entries(name='personal_main', backend='personal')), - )) + assert_that( + response, + has_entries( + total=3, + filtered=1, + items=contains(has_entries(name='personal_main', backend='personal')), + ), + ) response = self.client.directories.list_sources('main', backend='csv') - assert_that(response, has_entries( - total=3, - filtered=1, - items=contains(has_entries(name='csv_main', backend='csv')), - )) + assert_that( + response, + has_entries( + total=3, + filtered=1, + items=contains(has_entries(name='csv_main', backend='csv')), + ), + ) response = self.client.directories.list_sources('main', search='s') - assert_that(response, has_entries( - total=3, - filtered=2, - items=contains( - has_entries(name='csv_main', backend='csv'), - has_entries(name='personal_main', backend='personal'), + assert_that( + response, + has_entries( + total=3, + filtered=2, + items=contains( + has_entries(name='csv_main', backend='csv'), + has_entries(name='personal_main', backend='personal'), + ), ), - )) + ) diff --git a/integration_tests/suite/test_service_discovery_service.py b/integration_tests/suite/test_service_discovery_service.py index 29b10feb..d602a5c2 100644 --- a/integration_tests/suite/test_service_discovery_service.py +++ b/integration_tests/suite/test_service_discovery_service.py @@ -3,11 +3,7 @@ from unittest import skip -from hamcrest import ( - assert_that, - contains, - has_entry, -) +from hamcrest import assert_that, contains, has_entry from xivo_test_helpers import until @@ -22,34 +18,22 @@ class TestDiscoveredWazoUser(BaseDirdIntegrationTest): { 'name': 'default_display', 'columns': [ - { - 'title': 'Firstname', - 'field': 'firstname', - }, - { - 'title': 'Lastname', - 'field': 'lastname', - }, - { - 'title': 'Number', - 'default': '', - 'field': 'number', - }, - { - 'title': 'Mobile', - 'default': '', - 'field': 'mobile_phone_number', - }, + {'title': 'Firstname', 'field': 'firstname'}, + {'title': 'Lastname', 'field': 'lastname'}, + {'title': 'Number', 'default': '', 'field': 'number'}, + {'title': 'Mobile', 'default': '', 'field': 'mobile_phone_number'}, ], - }, + } ] def test_that_the_source_is_loaded(self): - def test(): result = self.lookup('dyl', 'default') - assert_that(result['results'], - contains(has_entry('column_values', - contains('Bob', 'Dylan', '1000', '')))) + assert_that( + result['results'], + contains( + has_entry('column_values', contains('Bob', 'Dylan', '1000', '')) + ), + ) until.assert_(test, tries=3) diff --git a/integration_tests/suite/test_sources.py b/integration_tests/suite/test_sources.py index 015bc7bd..8f5d8918 100644 --- a/integration_tests/suite/test_sources.py +++ b/integration_tests/suite/test_sources.py @@ -1,13 +1,7 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from hamcrest import ( - assert_that, - calling, - contains, - contains_inanyorder, - has_properties, -) +from hamcrest import assert_that, calling, contains, contains_inanyorder, has_properties from xivo_test_helpers.hamcrest.raises import raises from .helpers.base import BaseDirdIntegrationTest @@ -29,32 +23,45 @@ class TestList(BaseDirdIntegrationTest): @fixtures.csv_source(name='cde') def test_search(self, cde, bcd, abc): result = self.client.sources.list() - self.assert_list_result(result, contains_inanyorder( - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - self._source_to_dict('csv', **cde), - ), total=3, filtered=3) + self.assert_list_result( + result, + contains_inanyorder( + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + self._source_to_dict('csv', **cde), + ), + total=3, + filtered=3, + ) result = self.client.sources.list(name='abc') - self.assert_list_result(result, contains( - self._source_to_dict('ldap', **abc), - ), total=3, filtered=1) + self.assert_list_result( + result, contains(self._source_to_dict('ldap', **abc)), total=3, filtered=1 + ) result = self.client.sources.list(backend='csv') - self.assert_list_result(result, contains( - self._source_to_dict('csv', **cde), - ), total=3, filtered=1) + self.assert_list_result( + result, contains(self._source_to_dict('csv', **cde)), total=3, filtered=1 + ) result = self.client.sources.list(uuid=bcd['uuid']) - self.assert_list_result(result, contains( - self._source_to_dict('personal', **bcd), - ), total=3, filtered=1) + self.assert_list_result( + result, + contains(self._source_to_dict('personal', **bcd)), + total=3, + filtered=1, + ) result = self.client.sources.list(search='b') - self.assert_list_result(result, contains_inanyorder( - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - ), total=3, filtered=2) + self.assert_list_result( + result, + contains_inanyorder( + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + ), + total=3, + filtered=2, + ) @fixtures.ldap_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @fixtures.personal_source(name='bcd', token=VALID_TOKEN_SUB_TENANT) @@ -63,36 +70,52 @@ def test_multi_tenant(self, bcd, abc): sub_tenant_client = self.get_client(VALID_TOKEN_SUB_TENANT) result = main_tenant_client.sources.list() - self.assert_list_result(result, contains( - self._source_to_dict('ldap', **abc), - ), total=1, filtered=1) + self.assert_list_result( + result, contains(self._source_to_dict('ldap', **abc)), total=1, filtered=1 + ) result = main_tenant_client.sources.list(recurse=True) - self.assert_list_result(result, contains( - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - ), total=2, filtered=2) + self.assert_list_result( + result, + contains( + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + ), + total=2, + filtered=2, + ) result = main_tenant_client.sources.list(tenant_uuid=SUB_TENANT, recurse=True) - self.assert_list_result(result, contains( - self._source_to_dict('personal', **bcd), - ), total=1, filtered=1) + self.assert_list_result( + result, + contains(self._source_to_dict('personal', **bcd)), + total=1, + filtered=1, + ) result = sub_tenant_client.sources.list() - self.assert_list_result(result, contains( - self._source_to_dict('personal', **bcd), - ), total=1, filtered=1) + self.assert_list_result( + result, + contains(self._source_to_dict('personal', **bcd)), + total=1, + filtered=1, + ) result = sub_tenant_client.sources.list(recurse=True) - self.assert_list_result(result, contains( - self._source_to_dict('personal', **bcd), - ), total=1, filtered=1) + self.assert_list_result( + result, + contains(self._source_to_dict('personal', **bcd)), + total=1, + filtered=1, + ) assert_that( calling(sub_tenant_client.sources.list).with_args( - tenant_uuid=MAIN_TENANT, recurse=True, + tenant_uuid=MAIN_TENANT, recurse=True + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))) ) @fixtures.ldap_source(name='abc') @@ -100,37 +123,62 @@ def test_multi_tenant(self, bcd, abc): @fixtures.csv_source(name='cde') def test_pagination(self, cde, bcd, abc): result = self.client.sources.list(order='name') - self.assert_list_result(result, contains( - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - self._source_to_dict('csv', **cde), - ), total=3, filtered=3) + self.assert_list_result( + result, + contains( + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + self._source_to_dict('csv', **cde), + ), + total=3, + filtered=3, + ) result = self.client.sources.list(order='backend') - self.assert_list_result(result, contains( - self._source_to_dict('csv', **cde), - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - ), total=3, filtered=3) + self.assert_list_result( + result, + contains( + self._source_to_dict('csv', **cde), + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + ), + total=3, + filtered=3, + ) result = self.client.sources.list(order='name', direction='desc') - self.assert_list_result(result, contains( - self._source_to_dict('csv', **cde), - self._source_to_dict('personal', **bcd), - self._source_to_dict('ldap', **abc), - ), total=3, filtered=3) + self.assert_list_result( + result, + contains( + self._source_to_dict('csv', **cde), + self._source_to_dict('personal', **bcd), + self._source_to_dict('ldap', **abc), + ), + total=3, + filtered=3, + ) result = self.client.sources.list(order='name', limit=2) - self.assert_list_result(result, contains( - self._source_to_dict('ldap', **abc), - self._source_to_dict('personal', **bcd), - ), total=3, filtered=3) + self.assert_list_result( + result, + contains( + self._source_to_dict('ldap', **abc), + self._source_to_dict('personal', **bcd), + ), + total=3, + filtered=3, + ) result = self.client.sources.list(order='name', offset=2) - self.assert_list_result(result, contains( - self._source_to_dict('csv', **cde), - ), total=3, filtered=3) + self.assert_list_result( + result, contains(self._source_to_dict('csv', **cde)), total=3, filtered=3 + ) @staticmethod def _source_to_dict(backend, uuid, name, tenant_uuid, **ignored): - return {'uuid': uuid, 'name': name, 'backend': backend, 'tenant_uuid': tenant_uuid} + return { + 'uuid': uuid, + 'name': name, + 'backend': backend, + 'tenant_uuid': tenant_uuid, + } diff --git a/integration_tests/suite/test_tenant_migration.py b/integration_tests/suite/test_tenant_migration.py index 86f83c0a..7c3c7ec8 100644 --- a/integration_tests/suite/test_tenant_migration.py +++ b/integration_tests/suite/test_tenant_migration.py @@ -3,12 +3,7 @@ from uuid import uuid4 from contextlib import closing -from hamcrest import ( - assert_that, - contains, - empty, - has_entries, -) +from hamcrest import assert_that, contains, empty, has_entries from .helpers.base import BasePhonebookTestCase from .helpers.constants import DIRD_TOKEN_TENANT @@ -20,7 +15,6 @@ def new_uuid(): class TestTenantMigration(BasePhonebookTestCase): - @classmethod def setUpClass(cls): super().setUpClass() @@ -31,7 +25,11 @@ def test_tenant_uuid_migration(self): {'name': 'foo', 'old_uuid': new_uuid(), 'new_uuid': new_uuid()}, {'name': 'bar', 'old_uuid': new_uuid(), 'new_uuid': new_uuid()}, # This tenant does not exist in wazo-auth - {'name': 'unknown', 'old_uuid': unknown_tenant_uuid, 'new_uuid': unknown_tenant_uuid}, + { + 'name': 'unknown', + 'old_uuid': unknown_tenant_uuid, + 'new_uuid': unknown_tenant_uuid, + }, ] # insert the old tenants in the dird DB @@ -61,7 +59,8 @@ def test_tenant_uuid_migration(self): # Generate the POST body with the names and new UUIDS body = [ {'uuid': t['new_uuid'], 'name': t['name']} - for t in tenants if t['name'] != 'unknown' # unknown does not exist in auth + for t in tenants + if t['name'] != 'unknown' # unknown does not exist in auth ] # Add an extra tenant that is not in wazo-dird body.append({'uuid': new_uuid(), 'name': 'ignored'}) @@ -82,48 +81,58 @@ def test_tenant_uuid_migration(self): assert_that( self.list_phonebooks(tenants[0]['name']).json(), has_entries( - items=contains(has_entries( - id=phonebook_0['id'], - tenant_uuid=tenants[0]['new_uuid'], - name=phonebook_0['name'], - description=phonebook_0['description'], - )), + items=contains( + has_entries( + id=phonebook_0['id'], + tenant_uuid=tenants[0]['new_uuid'], + name=phonebook_0['name'], + description=phonebook_0['description'], + ) + ), total=1, - ) + ), ) self.set_tenants(tenants[1]['name']) assert_that( self.list_phonebooks(tenants[1]['name']).json(), has_entries( - items=contains(has_entries( - id=phonebook_1['id'], - tenant_uuid=tenants[1]['new_uuid'], - name=phonebook_1['name'], - description=phonebook_1['description'], - )), + items=contains( + has_entries( + id=phonebook_1['id'], + tenant_uuid=tenants[1]['new_uuid'], + name=phonebook_1['name'], + description=phonebook_1['description'], + ) + ), total=1, - ) + ), ) self.set_tenants(tenants[2]['name']) assert_that( self.list_phonebooks(tenants[2]['name']).json(), has_entries( - items=contains(has_entries( - id=phonebook_2['id'], - tenant_uuid=tenants[2]['new_uuid'], - name=phonebook_2['name'], - description=phonebook_2['description'], - )), + items=contains( + has_entries( + id=phonebook_2['id'], + tenant_uuid=tenants[2]['new_uuid'], + name=phonebook_2['name'], + description=phonebook_2['description'], + ) + ), total=1, - ) + ), ) # check that migrated tenants are deleted with closing(self.Session()) as s: - migrated_tenants = [t['old_uuid'] for t in tenants if t['name'] != 'unknown'] - matching_tenants = s.query( - database.Tenant, - ).filter(database.Tenant.uuid.in_(migrated_tenants)).all() + migrated_tenants = [ + t['old_uuid'] for t in tenants if t['name'] != 'unknown' + ] + matching_tenants = ( + s.query(database.Tenant) + .filter(database.Tenant.uuid.in_(migrated_tenants)) + .all() + ) assert_that(matching_tenants, empty()) diff --git a/integration_tests/suite/test_wazo_user_backend.py b/integration_tests/suite/test_wazo_user_backend.py index 7fb4ad6b..0ce09fe1 100644 --- a/integration_tests/suite/test_wazo_user_backend.py +++ b/integration_tests/suite/test_wazo_user_backend.py @@ -14,14 +14,8 @@ from xivo_test_helpers import until -from .helpers.base import ( - BaseDirdIntegrationTest, - DirdAssetRunningTestCase, -) -from .helpers.config import ( - new_wazo_users_config, - new_wazo_users_multiple_wazo_config, -) +from .helpers.base import BaseDirdIntegrationTest, DirdAssetRunningTestCase +from .helpers.config import new_wazo_users_config, new_wazo_users_multiple_wazo_config from .helpers.constants import MAIN_TENANT from .base_dird_integration_test import BackendWrapper @@ -34,17 +28,15 @@ class TestWazoUser(DirdAssetRunningTestCase): def setUp(self): super().setUp() self.backend = BackendWrapper( - 'wazo', - { - 'config': self.backend_config(), - 'api': Mock(), - } + 'wazo', {'config': self.backend_config(), 'api': Mock()} ) - self._dylan = {'id': 42, - 'firstname': 'Bob', - 'lastname': 'Dylan', - 'exten': '1000', - 'voicemail_number': '1234'} + self._dylan = { + 'id': 42, + 'firstname': 'Bob', + 'lastname': 'Dylan', + 'exten': '1000', + 'voicemail_number': '1234', + } def tearDown(self): self.backend.unload() @@ -89,12 +81,19 @@ def test_that_relations_are_present(self): results = self.backend.search_raw('john') relations = results[0].relations - assert_that(relations, equal_to({'xivo_id': self.uuid, - 'agent_id': 3, - 'endpoint_id': 2, - 'user_id': 1, - 'user_uuid': '7ca42f43-8bd9-4a26-acb8-cb756f42bebb', - 'source_entry_id': '1'})) + assert_that( + relations, + equal_to( + { + 'xivo_id': self.uuid, + 'agent_id': 3, + 'endpoint_id': 2, + 'user_id': 1, + 'user_uuid': '7ca42f43-8bd9-4a26-acb8-cb756f42bebb', + 'source_entry_id': '1', + } + ), + ) def test_no_result(self): results = self.backend.search('frack') @@ -124,9 +123,12 @@ def test_no_result_until_started(self): def test(): result = self.lookup('dyl', 'default') - assert_that(result['results'], - contains(has_entry('column_values', - contains('Bob', 'Dylan', '1000', '')))) + assert_that( + result['results'], + contains( + has_entry('column_values', contains('Bob', 'Dylan', '1000', '')) + ), + ) until.assert_(test, tries=10) @@ -142,37 +144,43 @@ def test_lookup_multiple_wazo(self): expected_result = [ { 'column_values': ['Charles', 'European', '9012'], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77e1europe', - 'agent_id': None, - 'endpoint_id': 42, - 'user_id': 100, - 'user_uuid': 'ce36bbb4-ae97-4f7d-8a36-d82b96120418', - 'source_entry_id': '100'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77e1europe', + 'agent_id': None, + 'endpoint_id': 42, + 'user_id': 100, + 'user_uuid': 'ce36bbb4-ae97-4f7d-8a36-d82b96120418', + 'source_entry_id': '100', + }, 'source': 'wazo_europe', 'backend': 'wazo', }, { 'column_values': ['Mary', 'Sue', '1465'], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': 2, - 'user_id': 2, - 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', - 'source_entry_id': '2'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': 2, + 'user_id': 2, + 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', + 'source_entry_id': '2', + }, 'source': 'wazo_america', 'backend': 'wazo', }, { 'column_values': ['Charles', 'Kenedy', ''], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': None, - 'user_id': 100, - 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', - 'source_entry_id': '100'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': None, + 'user_id': 100, + 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', + 'source_entry_id': '100', + }, 'source': 'wazo_america', 'backend': 'wazo', - } + }, ] assert_that(result['results'], contains_inanyorder(*expected_result)) @@ -183,16 +191,17 @@ def test_favorites_multiple_wazo(self): result = self.favorites('default') - assert_that(result['results'], contains_inanyorder( - has_entries( - source='wazo_asia', - column_values=contains('Alice', None, '6543'), + assert_that( + result['results'], + contains_inanyorder( + has_entries( + source='wazo_asia', column_values=contains('Alice', None, '6543') + ), + has_entries( + source='wazo_america', column_values=contains('John', 'Doe', '1234') + ), ), - has_entries( - source='wazo_america', - column_values=contains('John', 'Doe', '1234'), - ), - )) + ) class TestWazoUserMultipleWazoOneMissing(BaseDirdIntegrationTest): @@ -206,15 +215,17 @@ def test_lookup_multiple_wazo(self): expected_result = [ { 'column_values': ['John', 'Doe', '1234'], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': 3, - 'endpoint_id': 2, - 'user_id': 1, - 'user_uuid': '7ca42f43-8bd9-4a26-acb8-cb756f42bebb', - 'source_entry_id': '1'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': 3, + 'endpoint_id': 2, + 'user_id': 1, + 'user_uuid': '7ca42f43-8bd9-4a26-acb8-cb756f42bebb', + 'source_entry_id': '1', + }, 'source': 'wazo_america', - 'backend': 'wazo' - }, + 'backend': 'wazo', + } ] assert_that(result['results'], contains_inanyorder(*expected_result)) @@ -231,26 +242,30 @@ def test_lookup_multiple_wazo(self): expected_result = [ { 'column_values': ['Mary', 'Sue', '1465'], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': 2, - 'user_id': 2, - 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', - 'source_entry_id': '2'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': 2, + 'user_id': 2, + 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', + 'source_entry_id': '2', + }, 'source': 'wazo_america', - 'backend': 'wazo' + 'backend': 'wazo', }, { 'column_values': ['Charles', 'Kenedy', ''], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': None, - 'user_id': 100, - 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', - 'source_entry_id': '100'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': None, + 'user_id': 100, + 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', + 'source_entry_id': '100', + }, 'source': 'wazo_america', - 'backend': 'wazo' - } + 'backend': 'wazo', + }, ] assert_that(result['results'], contains_inanyorder(*expected_result)) @@ -267,26 +282,30 @@ def test_lookup_multiple_wazo(self): expected_result = [ { 'column_values': ['Mary', 'Sue', '1465'], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': 2, - 'user_id': 2, - 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', - 'source_entry_id': '2'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': 2, + 'user_id': 2, + 'user_uuid': 'df486ed4-975b-4316-815c-e19c3c1811c4', + 'source_entry_id': '2', + }, 'source': 'wazo_america', - 'backend': 'wazo' + 'backend': 'wazo', }, { 'column_values': ['Charles', 'Kenedy', ''], - 'relations': {'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', - 'agent_id': None, - 'endpoint_id': None, - 'user_id': 100, - 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', - 'source_entry_id': '100'}, + 'relations': { + 'xivo_id': '6fa459ea-ee8a-3ca4-894e-db77eamerica', + 'agent_id': None, + 'endpoint_id': None, + 'user_id': 100, + 'user_uuid': '9dfa2706-cd85-4130-82be-c54cc15e8410', + 'source_entry_id': '100', + }, 'source': 'wazo_america', - 'backend': 'wazo' - } + 'backend': 'wazo', + }, ] assert_that(result['results'], contains_inanyorder(*expected_result)) diff --git a/integration_tests/suite/test_wazo_user_contacts.py b/integration_tests/suite/test_wazo_user_contacts.py index d671fcf5..a29eb8e4 100644 --- a/integration_tests/suite/test_wazo_user_contacts.py +++ b/integration_tests/suite/test_wazo_user_contacts.py @@ -41,40 +41,48 @@ def setUp(self): def test_list(self): result = self.contacts(self.client, self.source_uuid) - assert_that(result, has_entries( - total=4, - filtered=4, - items=contains_inanyorder( - has_entries( - id=1, - uuid=uuid_(), - firstname='John', - lastname='Doe', - exten='1234', - voicemail_number=None, - mobile_phone_number='+14184765458', - email='john@doe.com', + assert_that( + result, + has_entries( + total=4, + filtered=4, + items=contains_inanyorder( + has_entries( + id=1, + uuid=uuid_(), + firstname='John', + lastname='Doe', + exten='1234', + voicemail_number=None, + mobile_phone_number='+14184765458', + email='john@doe.com', + ), + has_entries(firstname='Mary'), + has_entries(firstname='Bob'), + has_entries(firstname='Charles'), ), - has_entries(firstname='Mary'), - has_entries(firstname='Bob'), - has_entries(firstname='Charles'), ), - )) - - assert_that(result['items'][0].keys(), contains_inanyorder( - 'id', - 'uuid', - 'firstname', - 'lastname', - 'exten', - 'voicemail_number', - 'mobile_phone_number', - 'email', - )) + ) + + assert_that( + result['items'][0].keys(), + contains_inanyorder( + 'id', + 'uuid', + 'firstname', + 'lastname', + 'exten', + 'voicemail_number', + 'mobile_phone_number', + 'email', + ), + ) assert_that( calling(self.contacts).with_args(self.client, UNKNOWN_UUID), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) def test_multi_tenant(self): @@ -83,16 +91,18 @@ def test_multi_tenant(self): assert_that( calling(self.contacts).with_args(sub_tenant_client, self.source_uuid), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) assert_that( calling(self.contacts).with_args( - sub_tenant_client, - self.source_uuid, - tenant_uuid=MAIN_TENANT + sub_tenant_client, self.source_uuid, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), ) assert_that( @@ -102,11 +112,11 @@ def test_multi_tenant(self): assert_that( calling(self.contacts).with_args( - main_tenant_client, - self.source_uuid, - tenant_uuid=SUB_TENANT, + main_tenant_client, self.source_uuid, tenant_uuid=SUB_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) ), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))), ) def test_with_no_confd(self): @@ -114,17 +124,14 @@ def test_with_no_confd(self): try: assert_that( calling(self.contacts).with_args(self.client, self.source_uuid), - raises(Exception).matching(has_properties( - response=has_properties(status_code=503), - )) + raises(Exception).matching( + has_properties(response=has_properties(status_code=503)) + ), ) finally: self.start_service('america') def contacts(self, client, uuid, *args, **kwargs): return client.backends.list_contacts_from_source( - backend=BACKEND, - source_uuid=uuid, - *args, - **kwargs + backend=BACKEND, source_uuid=uuid, *args, **kwargs ) diff --git a/integration_tests/suite/test_wazo_user_http.py b/integration_tests/suite/test_wazo_user_http.py index 7cbc2139..daa6abe0 100644 --- a/integration_tests/suite/test_wazo_user_http.py +++ b/integration_tests/suite/test_wazo_user_http.py @@ -32,12 +32,7 @@ class BaseWazoCRUDTestCase(BaseDirdIntegrationTest): asset = 'all_routes' - valid_body = { - 'name': 'internal', - 'auth': { - 'key_file': '/path/to/the/key/file', - } - } + valid_body = {'name': 'internal', 'auth': {'key_file': '/path/to/the/key/file'}} @classmethod def setUpClass(cls): @@ -57,7 +52,7 @@ def assert_unknown_source_exception(self, source_uuid, exception): error_id='unknown-source', resource='sources', details=has_entries(uuid=source_uuid), - ) + ), ) def get_client(self, token=VALID_TOKEN_MAIN_TENANT): @@ -73,7 +68,6 @@ def source(self, client, *args, **kwargs): class TestDelete(BaseWazoCRUDTestCase): - @fixtures.wazo_source(name='foobar') def test_delete(self, foobar): assert_that( @@ -83,7 +77,9 @@ def test_delete(self, foobar): assert_that( calling(self.client.wazo_source.get).with_args(foobar['uuid']), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -113,46 +109,28 @@ def test_delete_multi_tenant(self, sub, main): class TestList(BaseWazoCRUDTestCase): - @fixtures.wazo_source(name='abc') @fixtures.wazo_source(name='bcd') @fixtures.wazo_source(name='cde') def test_searches(self, c, b, a): assert_that( self.client.wazo_source.list(), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( self.client.wazo_source.list(name='abc'), - has_entries( - items=contains(a), - total=3, - filtered=1, - ) + has_entries(items=contains(a), total=3, filtered=1), ) assert_that( self.client.wazo_source.list(uuid=c['uuid']), - has_entries( - items=contains(c), - total=3, - filtered=1, - ) + has_entries(items=contains(c), total=3, filtered=1), ) result = self.client.wazo_source.list(search='b') assert_that( - result, - has_entries( - items=contains_inanyorder(a, b), - total=3, - filtered=2, - ) + result, has_entries(items=contains_inanyorder(a, b), total=3, filtered=2) ) @fixtures.wazo_source(name='abc') @@ -161,38 +139,22 @@ def test_searches(self, c, b, a): def test_pagination(self, c, b, a): assert_that( self.client.wazo_source.list(order='name'), - has_entries( - items=contains(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b, c), total=3, filtered=3), ) assert_that( self.client.wazo_source.list(order='name', direction='desc'), - has_entries( - items=contains(c, b, a), - total=3, - filtered=3, - ) + has_entries(items=contains(c, b, a), total=3, filtered=3), ) assert_that( self.client.wazo_source.list(order='name', limit=2), - has_entries( - items=contains(a, b), - total=3, - filtered=3, - ) + has_entries(items=contains(a, b), total=3, filtered=3), ) assert_that( self.client.wazo_source.list(order='name', offset=2), - has_entries( - items=contains(c), - total=3, - filtered=3, - ) + has_entries(items=contains(c), total=3, filtered=3), ) @fixtures.wazo_source(name='abc', token=VALID_TOKEN_MAIN_TENANT) @@ -204,43 +166,26 @@ def test_multi_tenant(self, c, b, a): assert_that( main_tenant_client.wazo_source.list(), - has_entries( - items=contains_inanyorder(a, b), - total=2, - filtered=2, - ) + has_entries(items=contains_inanyorder(a, b), total=2, filtered=2), ) assert_that( main_tenant_client.wazo_source.list(recurse=True), - has_entries( - items=contains_inanyorder(a, b, c), - total=3, - filtered=3, - ) + has_entries(items=contains_inanyorder(a, b, c), total=3, filtered=3), ) assert_that( sub_tenant_client.wazo_source.list(), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) assert_that( sub_tenant_client.wazo_source.list(recurse=True), - has_entries( - items=contains_inanyorder(c), - total=1, - filtered=1, - ) + has_entries(items=contains_inanyorder(c), total=1, filtered=1), ) class TestPost(BaseWazoCRUDTestCase): - def test_post(self): try: self.client.wazo_source.create({}) @@ -261,8 +206,8 @@ def test_post(self): assert_that( calling(self.client.wazo_source.create).with_args(self.valid_body), raises(Exception).matching( - has_properties(response=has_properties(status_code=409)), - ) + has_properties(response=has_properties(status_code=409)) + ), ) def test_multi_tenant(self): @@ -272,28 +217,33 @@ def test_multi_tenant(self): with self.source(main_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=MAIN_TENANT)) - with self.source(main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT) as result: + with self.source( + main_tenant_client, self.valid_body, tenant_uuid=SUB_TENANT + ) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) with self.source(sub_tenant_client, self.valid_body) as result: assert_that(result, has_entries(uuid=uuid_(), tenant_uuid=SUB_TENANT)) assert_that( - calling( - sub_tenant_client.wazo_source.create - ).with_args(self.valid_body, tenant_uuid=MAIN_TENANT), - raises(Exception).matching(has_properties(response=has_properties(status_code=401))), + calling(sub_tenant_client.wazo_source.create).with_args( + self.valid_body, tenant_uuid=MAIN_TENANT + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=401)) + ), ) with self.source(main_tenant_client, self.valid_body): assert_that( - calling(sub_tenant_client.wazo_source.create).with_args(self.valid_body), + calling(sub_tenant_client.wazo_source.create).with_args( + self.valid_body + ), not_(raises(Exception)), ) class TestPut(BaseWazoCRUDTestCase): - def setUp(self): super().setUp() self.new_body = { @@ -301,9 +251,7 @@ def setUp(self): 'auth': {'username': 'foo', 'password': 'secret'}, 'searched_columns': ['firstname'], 'first_matched_columns': ['exten'], - 'format_columns': { - 'name': '{firstname} {lastname}', - } + 'format_columns': {'name': '{firstname} {lastname}'}, } @fixtures.wazo_source(name='foobar') @@ -311,12 +259,18 @@ def setUp(self): def test_put(self, foobar, other): assert_that( calling(self.client.wazo_source.edit).with_args(foobar['uuid'], other), - raises(Exception).matching(has_properties(response=has_properties(status_code=409))) + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ), ) assert_that( - calling(self.client.wazo_source.edit).with_args(UNKNOWN_UUID, self.new_body), - raises(Exception).matching(has_properties(response=has_properties(status_code=404))) + calling(self.client.wazo_source.edit).with_args( + UNKNOWN_UUID, self.new_body + ), + raises(Exception).matching( + has_properties(response=has_properties(status_code=404)) + ), ) try: @@ -335,7 +289,9 @@ def test_put(self, foobar, other): self.fail('Should have raised') assert_that( - calling(self.client.wazo_source.edit).with_args(foobar['uuid'], self.new_body), + calling(self.client.wazo_source.edit).with_args( + foobar['uuid'], self.new_body + ), not_(raises(Exception)), ) @@ -350,7 +306,7 @@ def test_put(self, foobar, other): searched_columns=['firstname'], first_matched_columns=['exten'], format_columns={'name': '{firstname} {lastname}'}, - ) + ), ) @fixtures.wazo_source(name='foomain', token=VALID_TOKEN_MAIN_TENANT) @@ -361,9 +317,11 @@ def test_put_multi_tenant(self, sub, main): assert_that( calling(sub_tenant_client.wazo_source.edit).with_args(main['uuid'], sub), - not_(raises(Exception).matching( - has_properties(response=has_properties(status_code=409))) - ) + not_( + raises(Exception).matching( + has_properties(response=has_properties(status_code=409)) + ) + ), ) try: @@ -374,13 +332,14 @@ def test_put_multi_tenant(self, sub, main): self.fail('Should have raised') assert_that( - calling(main_tenant_client.wazo_source.edit).with_args(sub['uuid'], self.new_body), + calling(main_tenant_client.wazo_source.edit).with_args( + sub['uuid'], self.new_body + ), not_(raises(Exception)), ) class TestGet(BaseWazoCRUDTestCase): - @fixtures.wazo_source(name='foobar') def test_get(self, wazo): response = self.client.wazo_source.get(wazo['uuid']) diff --git a/setup.py b/setup.py index 9de335b3..a6b69d92 100755 --- a/setup.py +++ b/setup.py @@ -19,13 +19,13 @@ def run(self): class BabelWrapper(object): - def compile_catalog(self, *args, **kwargs): return self.babel.compile_catalog(*args, **kwargs) @property def babel(self): from babel.messages import frontend as babel + return babel @@ -33,32 +33,23 @@ def babel(self): setup( name='wazo-dird', version='1.2', - description='Wazo Directory Daemon', - author='Wazo Authors', author_email='dev@wazo.community', - url='http://wazo.community', - packages=find_packages(), - include_package_data=True, setup_requires=['babel'], install_requires=['babel'], zip_safe=False, - package_data={ - 'wazo_dird.plugins': ['*/api.yml'] + package_data={'wazo_dird.plugins': ['*/api.yml']}, + cmdclass={ + 'build': build, + 'install_lib': install_lib, + 'compile_catalog': babel_wrapper.compile_catalog, }, - - cmdclass={'build': build, - 'install_lib': install_lib, - 'compile_catalog': babel_wrapper.compile_catalog}, - entry_points={ - 'console_scripts': [ - 'wazo-dird=wazo_dird.main:main', - ], + 'console_scripts': ['wazo-dird=wazo_dird.main:main'], 'wazo_dird.services': [ 'cleanup = wazo_dird.plugins.cleanup_service.plugin:StorageCleanupServicePlugin', 'config = wazo_dird.plugins.config_service.plugin:ConfigServicePlugin', @@ -113,5 +104,5 @@ def babel(self): 'wazo_backend = wazo_dird.plugins.wazo_user_backend.plugin:WazoUserView', 'profile_sources_view = wazo_dird.plugins.profile_sources.plugin:SourceViewPlugin', ], - } + }, ) diff --git a/wazo_dird/bus.py b/wazo_dird/bus.py index 53d80fa6..2a01fa7d 100644 --- a/wazo_dird/bus.py +++ b/wazo_dird/bus.py @@ -72,21 +72,24 @@ def _get_publisher(self): if not self._publisher: bus_connection = kombu.Connection(self._bus_url) bus_exchange = kombu.Exchange(self._exchange_name, type=self._exchange_type) - producer = kombu.Producer(bus_connection, exchange=bus_exchange, auto_declare=True) + producer = kombu.Producer( + bus_connection, exchange=bus_exchange, auto_declare=True + ) self._publisher = Publisher(producer, self._marshaler) return self._publisher class _Consumer(ConsumerMixin): - def __init__(self, connection, queues_and_callbacks): self.connection = connection self._queues_and_callbacks = queues_and_callbacks self._is_running = False def get_consumers(self, Consumer, channel): - return [Consumer(queue, callbacks=[callback]) - for (queue, callback) in self._queues_and_callbacks] + return [ + Consumer(queue, callbacks=[callback]) + for (queue, callback) in self._queues_and_callbacks + ] def is_running(self): return self._is_running diff --git a/wazo_dird/config.py b/wazo_dird/config.py index 8cbc580b..1deedbd6 100644 --- a/wazo_dird/config.py +++ b/wazo_dird/config.py @@ -4,10 +4,7 @@ import argparse from xivo.chain_map import ChainMap -from xivo.config_helper import ( - parse_config_file, - read_config_file_hierarchy, -) +from xivo.config_helper import parse_config_file, read_config_file_hierarchy from xivo.xivo_logging import get_log_level_by_name _DEFAULT_HTTPS_PORT = 9489 @@ -64,7 +61,7 @@ 'service_discovery': { 'template_path': '/etc/wazo-dird/templates.d/', 'services': {}, - }, + } }, 'user': 'www-data', 'bus': { @@ -94,42 +91,45 @@ def load(logger, argv): cli_config = _parse_cli_args(argv) file_config = read_config_file_hierarchy(ChainMap(cli_config, _DEFAULT_CONFIG)) reinterpreted_config = _get_reinterpreted_raw_values( - ChainMap(cli_config, file_config, _DEFAULT_CONFIG), + ChainMap(cli_config, file_config, _DEFAULT_CONFIG) ) key_file = _load_key_file(ChainMap(cli_config, file_config, _DEFAULT_CONFIG)) return ChainMap( - reinterpreted_config, - key_file, - cli_config, - file_config, - _DEFAULT_CONFIG, + reinterpreted_config, key_file, cli_config, file_config, _DEFAULT_CONFIG ) def _parse_cli_args(argv): parser = argparse.ArgumentParser() - parser.add_argument('-c', - '--config-file', - action='store', - help="The path where is the config file. Default: %(default)s") - parser.add_argument('-d', - '--debug', - action='store_true', - help="Log debug messages. Overrides log_level. Default: %(default)s") - parser.add_argument('-f', - '--foreground', - action='store_true', - help="Foreground, don't daemonize. Default: %(default)s") - parser.add_argument('-l', - '--log-level', - action='store', - help="Logs messages with LOG_LEVEL details. Must be one of:\n" - "critical, error, warning, info, debug. Default: %(default)s") - parser.add_argument('-u', - '--user', - action='store', - help="The owner of the process.") + parser.add_argument( + '-c', + '--config-file', + action='store', + help="The path where is the config file. Default: %(default)s", + ) + parser.add_argument( + '-d', + '--debug', + action='store_true', + help="Log debug messages. Overrides log_level. Default: %(default)s", + ) + parser.add_argument( + '-f', + '--foreground', + action='store_true', + help="Foreground, don't daemonize. Default: %(default)s", + ) + parser.add_argument( + '-l', + '--log-level', + action='store', + help="Logs messages with LOG_LEVEL details. Must be one of:\n" + "critical, error, warning, info, debug. Default: %(default)s", + ) + parser.add_argument( + '-u', '--user', action='store', help="The owner of the process." + ) parsed_args = parser.parse_args(argv) result = {} @@ -156,7 +156,12 @@ def _load_key_file(config): if not key_file: return {} - return {'auth': {'username': key_file['service_id'], 'password': key_file['service_key']}} + return { + 'auth': { + 'username': key_file['service_id'], + 'password': key_file['service_key'], + } + } def _get_reinterpreted_raw_values(config): diff --git a/wazo_dird/controller.py b/wazo_dird/controller.py index e6f95394..474d1557 100644 --- a/wazo_dird/controller.py +++ b/wazo_dird/controller.py @@ -27,7 +27,6 @@ def _signal_handler(signum, frame): class Controller: - def __init__(self, config): self.config = config init_db(config['db_uri']) diff --git a/wazo_dird/database/__init__.py b/wazo_dird/database/__init__.py index 30b700dd..1712673a 100644 --- a/wazo_dird/database/__init__.py +++ b/wazo_dird/database/__init__.py @@ -17,17 +17,10 @@ Tenant, User, ) -from .queries.base import ( - delete_user, -) +from .queries.base import delete_user from .queries.display import DisplayCRUD -from .queries.favorite import ( - FavoriteCRUD, -) -from .queries.personal import ( - PersonalContactCRUD, - PersonalContactSearchEngine, -) +from .queries.favorite import FavoriteCRUD +from .queries.personal import PersonalContactCRUD, PersonalContactSearchEngine from .queries.phonebook import ( PhonebookCRUD, PhonebookContactCRUD, diff --git a/wazo_dird/database/models.py b/wazo_dird/database/models.py index edea09d8..79d4439c 100644 --- a/wazo_dird/database/models.py +++ b/wazo_dird/database/models.py @@ -1,15 +1,11 @@ # Copyright 2016-2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from sqlalchemy import (Column, ForeignKey, Integer, schema, String, text, Text) +from sqlalchemy import Column, ForeignKey, Integer, schema, String, text, Text from sqlalchemy.orm import relationship from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.dialects.postgresql import ( - ARRAY, - HSTORE, - JSON, -) +from sqlalchemy.dialects.postgresql import ARRAY, HSTORE, JSON Base = declarative_base() @@ -24,9 +20,15 @@ class Contact(Base): schema.UniqueConstraint('phonebook_id', 'hash'), ) - uuid = Column(String(38), server_default=text('uuid_generate_v4()'), primary_key=True) - user_uuid = Column(String(38), ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE')) - phonebook_id = Column(Integer(), ForeignKey('dird_phonebook.id', ondelete='CASCADE')) + uuid = Column( + String(38), server_default=text('uuid_generate_v4()'), primary_key=True + ) + user_uuid = Column( + String(38), ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE') + ) + phonebook_id = Column( + Integer(), ForeignKey('dird_phonebook.id', ondelete='CASCADE') + ) hash = Column(String(40), nullable=False) @@ -38,19 +40,21 @@ class ContactFields(Base): name = Column(Text(), nullable=False, index=True) value = Column(Text(), index=True) contact_uuid = Column( - String(38), ForeignKey('dird_contact.uuid', ondelete='CASCADE'), nullable=False, + String(38), ForeignKey('dird_contact.uuid', ondelete='CASCADE'), nullable=False ) class Display(Base): __tablename__ = 'dird_display' - __table_args__ = ( - schema.UniqueConstraint('uuid', 'tenant_uuid'), - ) + __table_args__ = (schema.UniqueConstraint('uuid', 'tenant_uuid'),) - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) - tenant_uuid = Column(String(UUID_LENGTH), ForeignKey('dird_tenant.uuid', ondelete='CASCADE')) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) + tenant_uuid = Column( + String(UUID_LENGTH), ForeignKey('dird_tenant.uuid', ondelete='CASCADE') + ) name = Column(Text(), nullable=False) columns = relationship('DisplayColumn', viewonly=True) @@ -60,8 +64,12 @@ class DisplayColumn(Base): __tablename__ = 'dird_display_column' - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) - display_uuid = Column(String(UUID_LENGTH), ForeignKey('dird_display.uuid', ondelete='CASCADE')) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) + display_uuid = Column( + String(UUID_LENGTH), ForeignKey('dird_display.uuid', ondelete='CASCADE') + ) field = Column(Text()) title = Column(Text()) type = Column(Text()) @@ -81,9 +89,11 @@ class Favorite(Base): primary_key=True, ) contact_id = Column(Text(), primary_key=True) - user_uuid = Column(String(38), - ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), - primary_key=True) + user_uuid = Column( + String(38), + ForeignKey('dird_user.xivo_user_uuid', ondelete='CASCADE'), + primary_key=True, + ) class Phonebook(Base): @@ -115,8 +125,12 @@ class Profile(Base): schema.CheckConstraint('tenant_uuid = display_tenant_uuid'), ) - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) - tenant_uuid = Column(String(UUID_LENGTH), ForeignKey('dird_tenant.uuid', ondelete='CASCADE')) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) + tenant_uuid = Column( + String(UUID_LENGTH), ForeignKey('dird_tenant.uuid', ondelete='CASCADE') + ) name = Column(Text(), nullable=False) display_tenant_uuid = Column(String(UUID_LENGTH)) display_uuid = Column(String(UUID_LENGTH)) @@ -165,12 +179,13 @@ class ProfileService(Base): ), ) - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) profile_uuid = Column(String(UUID_LENGTH)) profile_tenant_uuid = Column(String(UUID_LENGTH)) service_uuid = Column( - String(UUID_LENGTH), - ForeignKey('dird_service.uuid', ondelete='CASCADE'), + String(UUID_LENGTH), ForeignKey('dird_service.uuid', ondelete='CASCADE') ) config = Column(JSON) @@ -183,7 +198,9 @@ class Service(Base): __tablename__ = 'dird_service' - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) name = Column(Text(), unique=True, nullable=False) @@ -195,7 +212,9 @@ class Source(Base): schema.UniqueConstraint('name', 'tenant_uuid'), ) - uuid = Column(String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True) + uuid = Column( + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True + ) name = Column(Text(), nullable=False) tenant_uuid = Column(String(UUID_LENGTH), ForeignKey('dird_tenant.uuid')) searched_columns = Column(ARRAY(Text)) @@ -210,9 +229,7 @@ class Tenant(Base): __tablename__ = 'dird_tenant' uuid = Column( - String(UUID_LENGTH), - server_default=text('uuid_generate_v4()'), - primary_key=True, + String(UUID_LENGTH), server_default=text('uuid_generate_v4()'), primary_key=True ) # DEPRECATED uuids should match wazo-auth and names should not be used # the field will be removed after an upgrade that forces an upgrade above version 19.02 diff --git a/wazo_dird/database/queries/base.py b/wazo_dird/database/queries/base.py index 025e6a1c..747052ce 100644 --- a/wazo_dird/database/queries/base.py +++ b/wazo_dird/database/queries/base.py @@ -8,10 +8,7 @@ from sqlalchemy import exc from xivo import sqlalchemy_helper from wazo_dird.exception import DatabaseServiceUnavailable -from wazo_dird.database import ( - Tenant, - User, -) +from wazo_dird.database import Tenant, User from .. import ContactFields @@ -34,7 +31,9 @@ def list_contacts_by_uuid(session, uuids): if not uuids: return [] - contact_fields = session.query(ContactFields).filter(ContactFields.contact_uuid.in_(uuids)) + contact_fields = session.query(ContactFields).filter( + ContactFields.contact_uuid.in_(uuids) + ) result = {} for contact_field in contact_fields.all(): uuid = contact_field.contact_uuid @@ -52,7 +51,6 @@ def compute_contact_hash(contact_info): class BaseDAO: - def __init__(self, Session): self._Session = Session diff --git a/wazo_dird/database/queries/display.py b/wazo_dird/database/queries/display.py index f988e848..fd966712 100644 --- a/wazo_dird/database/queries/display.py +++ b/wazo_dird/database/queries/display.py @@ -1,18 +1,11 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from sqlalchemy import ( - and_, - func, - text, -) +from sqlalchemy import and_, func, text from wazo_dird.database import schemas from wazo_dird.exception import NoSuchDisplay from .base import BaseDAO -from ..import ( - Display, - DisplayColumn, -) +from .. import Display, DisplayColumn class DisplayCRUD(BaseDAO): @@ -28,7 +21,9 @@ def count(self, visible_tenants, **list_params): def create(self, tenant_uuid, name, columns, uuid=None): with self.new_session() as s: self._create_tenant(s, tenant_uuid) - display = self._add_display(s, tenant_uuid=tenant_uuid, name=name, uuid=uuid) + display = self._add_display( + s, tenant_uuid=tenant_uuid, name=name, uuid=uuid + ) for column in columns: self._add_column(s, display_uuid=display.uuid, **column) s.flush() @@ -37,7 +32,9 @@ def create(self, tenant_uuid, name, columns, uuid=None): def delete(self, visible_tenants, display_uuid): filter_ = self._build_filter(visible_tenants, display_uuid) with self.new_session() as s: - nb_deleted = s.query(Display).filter(filter_).delete(synchronize_session=False) + nb_deleted = ( + s.query(Display).filter(filter_).delete(synchronize_session=False) + ) if not nb_deleted: raise NoSuchDisplay(display_uuid) @@ -50,7 +47,7 @@ def edit(self, visible_tenants, display_uuid, name, columns): raise NoSuchDisplay(display_uuid) s.query(DisplayColumn).filter( - DisplayColumn.display_uuid == display_uuid, + DisplayColumn.display_uuid == display_uuid ).delete(synchronize_session=False) display.name = name @@ -83,7 +80,9 @@ def _build_filter(self, visible_tenants, display_uuid): return filter_ - def _list_filter(self, visible_tenants, uuid=None, name=None, search=None, **list_params): + def _list_filter( + self, visible_tenants, uuid=None, name=None, search=None, **list_params + ): filter_ = text('true') if visible_tenants is not None: filter_ = and_(filter_, Display.tenant_uuid.in_(visible_tenants)) @@ -96,7 +95,9 @@ def _list_filter(self, visible_tenants, uuid=None, name=None, search=None, **lis filter_ = and_(filter_, Display.name.ilike(pattern)) return filter_ - def _paginate(self, query, limit=None, offset=None, order=None, direction=None, **ignored): + def _paginate( + self, query, limit=None, offset=None, order=None, direction=None, **ignored + ): if order and direction: field = None if order == 'name': diff --git a/wazo_dird/database/queries/favorite.py b/wazo_dird/database/queries/favorite.py index 258ec3f5..cc7d2696 100644 --- a/wazo_dird/database/queries/favorite.py +++ b/wazo_dird/database/queries/favorite.py @@ -4,26 +4,21 @@ from sqlalchemy import and_ from sqlalchemy.orm.session import make_transient -from wazo_dird.exception import ( - DuplicatedFavoriteException, - NoSuchFavorite, -) -from .. import ( - Favorite, - Source, -) +from wazo_dird.exception import DuplicatedFavoriteException, NoSuchFavorite +from .. import Favorite, Source from .base import BaseDAO class FavoriteCRUD(BaseDAO): - def create(self, xivo_user_uuid, backend, source_name, contact_id): with self.new_session() as s: user = self._get_dird_user(s, xivo_user_uuid) source = self._get_source(s, backend, source_name) - favorite = Favorite(source_uuid=source.uuid, - contact_id=contact_id, - user_uuid=user.xivo_user_uuid) + favorite = Favorite( + source_uuid=source.uuid, + contact_id=contact_id, + user_uuid=user.xivo_user_uuid, + ) s.add(favorite) self.flush_or_raise(s, DuplicatedFavoriteException) make_transient(favorite) @@ -31,7 +26,9 @@ def create(self, xivo_user_uuid, backend, source_name, contact_id): def delete(self, xivo_user_uuid, source_name, contact_id): with self.new_session() as s: - matching_source_uuids = s.query(Source.uuid).filter(Source.name == source_name).all() + matching_source_uuids = ( + s.query(Source.uuid).filter(Source.name == source_name).all() + ) if not matching_source_uuids: raise NoSuchFavorite((source_name, contact_id)) @@ -40,7 +37,9 @@ def delete(self, xivo_user_uuid, source_name, contact_id): Favorite.user_uuid == xivo_user_uuid, Favorite.source_uuid.in_(matching_source_uuids), ) - deleted = s.query(Favorite).filter(filter_).delete(synchronize_session=False) + deleted = ( + s.query(Favorite).filter(filter_).delete(synchronize_session=False) + ) s.commit() @@ -49,16 +48,18 @@ def delete(self, xivo_user_uuid, source_name, contact_id): def get(self, xivo_user_uuid): with self.new_session() as s: - favorites = s.query( - Favorite.contact_id, - Source.name - ).join(Source).filter(Favorite.user_uuid == xivo_user_uuid) + favorites = ( + s.query(Favorite.contact_id, Source.name) + .join(Source) + .filter(Favorite.user_uuid == xivo_user_uuid) + ) return [(f.name, f.contact_id) for f in favorites.all()] def _get_source(self, session, backend, source_name): - source = session.query(Source).filter(and_( - Source.name == source_name, - Source.backend == backend, - )).first() + source = ( + session.query(Source) + .filter(and_(Source.name == source_name, Source.backend == backend)) + .first() + ) return source diff --git a/wazo_dird/database/queries/personal.py b/wazo_dird/database/queries/personal.py index c18d58ed..d4b83e36 100644 --- a/wazo_dird/database/queries/personal.py +++ b/wazo_dird/database/queries/personal.py @@ -2,26 +2,11 @@ # SPDX-License-Identifier: GPL-3.0-or-later from unidecode import unidecode -from sqlalchemy import ( - and_, - distinct, - text, -) +from sqlalchemy import and_, distinct, text from sqlalchemy.sql.functions import ReturnTypeFromArgs -from wazo_dird.exception import ( - DuplicatedContactException, - NoSuchContact, -) -from .base import ( - BaseDAO, - compute_contact_hash, - list_contacts_by_uuid, -) -from .. import ( - Contact, - ContactFields, - User, -) +from wazo_dird.exception import DuplicatedContactException, NoSuchContact +from .base import BaseDAO, compute_contact_hash, list_contacts_by_uuid +from .. import Contact, ContactFields, User class unaccent(ReturnTypeFromArgs): @@ -29,14 +14,15 @@ class unaccent(ReturnTypeFromArgs): class PersonalContactSearchEngine(BaseDAO): - def __init__(self, Session, searched_columns=None, first_match_columns=None): super().__init__(Session) self._searched_columns = searched_columns or [] self._first_match_columns = first_match_columns or [] def find_first_personal_contact(self, xivo_user_uuid, term): - filter_ = self._new_strict_filter(xivo_user_uuid, term, self._first_match_columns) + filter_ = self._new_strict_filter( + xivo_user_uuid, term, self._first_match_columns + ) return self._find_personal_contacts_with_filter(filter_, limit=1) def find_personal_contacts(self, xivo_user_uuid, term): @@ -55,10 +41,12 @@ def _find_personal_contacts_with_filter(self, filter_, limit=None): return [] with self.new_session() as s: - base_query = (s.query(distinct(ContactFields.contact_uuid)) - .join(Contact) - .join(User) - .filter(filter_)) + base_query = ( + s.query(distinct(ContactFields.contact_uuid)) + .join(Contact) + .join(User) + .filter(filter_) + ) if limit: query = base_query.limit(limit) else: @@ -72,32 +60,36 @@ def _new_list_filter(self, xivo_user_uuid, uuids): if not uuids: return False - return and_(User.xivo_user_uuid == xivo_user_uuid, - ContactFields.contact_uuid.in_(uuids)) + return and_( + User.xivo_user_uuid == xivo_user_uuid, ContactFields.contact_uuid.in_(uuids) + ) def _new_search_filter(self, xivo_user_uuid, term, columns): if not columns: return False pattern = '%{}%'.format(unidecode(term)) - return and_(User.xivo_user_uuid == xivo_user_uuid, - unaccent(ContactFields.value).ilike(pattern), - ContactFields.name.in_(columns)) + return and_( + User.xivo_user_uuid == xivo_user_uuid, + unaccent(ContactFields.value).ilike(pattern), + ContactFields.name.in_(columns), + ) def _new_strict_filter(self, xivo_user_uuid, term, columns): if not columns: return False - return and_(User.xivo_user_uuid == xivo_user_uuid, - unaccent(ContactFields.value) == unidecode(term), - ContactFields.name.in_(columns)) + return and_( + User.xivo_user_uuid == xivo_user_uuid, + unaccent(ContactFields.value) == unidecode(term), + ContactFields.name.in_(columns), + ) def _new_user_contacts_filter(self, xivo_user_uuid): return User.xivo_user_uuid == xivo_user_uuid class PersonalContactCRUD(BaseDAO): - def list_personal_contacts(self, xivo_user_uuid=None): filter_ = text('true') if xivo_user_uuid: @@ -111,7 +103,7 @@ def list_personal_contacts(self, xivo_user_uuid=None): def create_personal_contact(self, xivo_user_uuid, contact_info): with self.new_session() as s: for contact in self._create_personal_contacts( - s, xivo_user_uuid, [contact_info], fail_on_duplicate=True, + s, xivo_user_uuid, [contact_info], fail_on_duplicate=True ): return contact @@ -120,7 +112,7 @@ def create_personal_contacts(self, xivo_user_uuid, contact_infos): return self._create_personal_contacts(s, xivo_user_uuid, contact_infos) def _create_personal_contacts( - self, session, xivo_user_uuid, contact_infos, fail_on_duplicate=False, + self, session, xivo_user_uuid, contact_infos, fail_on_duplicate=False ): hash_and_contact = {compute_contact_hash(c): c for c in contact_infos} user = self._get_dird_user(session, xivo_user_uuid) @@ -135,8 +127,7 @@ def _create_personal_contacts( for hash_ in to_add: contact_info = hash_and_contact[hash_] - contact_args = {'user_uuid': user.xivo_user_uuid, - 'hash': hash_} + contact_args = {'user_uuid': user.xivo_user_uuid, 'hash': hash_} contact_uuid = contact_info.get('id') if contact_uuid: contact_args['uuid'] = contact_uuid @@ -146,7 +137,9 @@ def _create_personal_contacts( contact_info['id'] = contact.uuid for name, value in contact_info.items(): - session.add(ContactFields(name=name, value=value, contact_uuid=contact.uuid)) + session.add( + ContactFields(name=name, value=value, contact_uuid=contact.uuid) + ) for hash_ in existing: contact_info = hash_and_contact[hash_] @@ -158,8 +151,7 @@ def _find_existing_contact_by_hash(self, session, xivo_user_uuid, hashes): if not hashes: return {} - filter_ = and_(Contact.user_uuid == xivo_user_uuid, - Contact.hash.in_(hashes)) + filter_ = and_(Contact.user_uuid == xivo_user_uuid, Contact.hash.in_(hashes)) pairs = session.query(Contact.hash, Contact.uuid).filter(filter_) return {p.hash: p.uuid for p in pairs.all()} @@ -171,17 +163,23 @@ def edit_personal_contact(self, xivo_user_uuid, contact_id, contact_info): s.rollback() raise DuplicatedContactException() contact_info['id'] = contact_id - for contact in self._create_personal_contacts(s, xivo_user_uuid, [contact_info]): + for contact in self._create_personal_contacts( + s, xivo_user_uuid, [contact_info] + ): return contact def get_personal_contact(self, xivo_user_uuid, contact_uuid): with self.new_session() as s: - filter_ = and_(User.xivo_user_uuid == xivo_user_uuid, - ContactFields.contact_uuid == contact_uuid) - contact_uuids = (s.query(distinct(ContactFields.contact_uuid)) - .join(Contact) - .join(User) - .filter(filter_)) + filter_ = and_( + User.xivo_user_uuid == xivo_user_uuid, + ContactFields.contact_uuid == contact_uuid, + ) + contact_uuids = ( + s.query(distinct(ContactFields.contact_uuid)) + .join(Contact) + .join(User) + .filter(filter_) + ) for contact in list_contacts_by_uuid(s, contact_uuids): return contact @@ -198,14 +196,18 @@ def delete_personal_contact(self, xivo_user_uuid, contact_uuid): self._delete_personal_contact(s, xivo_user_uuid, contact_uuid) def _delete_personal_contact(self, session, xivo_user_uuid, contact_uuid): - filter_ = and_(User.xivo_user_uuid == xivo_user_uuid, - ContactFields.contact_uuid == contact_uuid) + filter_ = and_( + User.xivo_user_uuid == xivo_user_uuid, + ContactFields.contact_uuid == contact_uuid, + ) nb_deleted = self._delete_personal_contacts_with_filter(session, filter_) if nb_deleted == 0: raise NoSuchContact(contact_uuid) def _delete_personal_contacts_with_filter(self, session, filter_): - contacts = session.query(Contact).join(ContactFields).join(User).filter(filter_).all() + contacts = ( + session.query(Contact).join(ContactFields).join(User).filter(filter_).all() + ) deleted = 0 for contact in contacts: session.delete(contact) diff --git a/wazo_dird/database/queries/phonebook.py b/wazo_dird/database/queries/phonebook.py index 8ef96ffa..d4bd1a92 100644 --- a/wazo_dird/database/queries/phonebook.py +++ b/wazo_dird/database/queries/phonebook.py @@ -2,12 +2,7 @@ # SPDX-License-Identifier: GPL-3.0-or-later from collections import defaultdict -from sqlalchemy import ( - and_, - distinct, - func, - or_, -) +from sqlalchemy import and_, distinct, func, or_ from wazo_dird.exception import ( DuplicatedContactException, @@ -16,28 +11,18 @@ NoSuchPhonebook, ) -from .base import ( - BaseDAO, - compute_contact_hash, - list_contacts_by_uuid, -) -from ..import ( - Contact, - ContactFields, - Phonebook, - Tenant, -) +from .base import BaseDAO, compute_contact_hash, list_contacts_by_uuid +from .. import Contact, ContactFields, Phonebook, Tenant class PhonebookContactSearchEngine(BaseDAO): - def __init__( - self, - Session, - tenant_uuid, - phonebook_id, - searched_columns=None, - first_match_columns=None, + self, + Session, + tenant_uuid, + phonebook_id, + searched_columns=None, + first_match_columns=None, ): super().__init__(Session) self._searched_columns = searched_columns @@ -93,14 +78,10 @@ def _new_search_filter(self, pattern, columns): if not columns: return False - return and_( - ContactFields.value.ilike(pattern), - ContactFields.name.in_(columns), - ) + return and_(ContactFields.value.ilike(pattern), ContactFields.name.in_(columns)) class PhonebookContactCRUD(BaseDAO): - def count(self, tenant_uuid, phonebook_id, search=None): with self.new_session() as s: phonebook = self._get_phonebook(s, tenant_uuid, phonebook_id) @@ -146,7 +127,9 @@ def edit(self, tenant_uuid, phonebook_id, contact_uuid, contact_body): contact = self._get_contact(s, tenant_uuid, phonebook.id, contact_uuid) contact.hash = hash_ self.flush_or_raise(s, DuplicatedContactException) - s.query(ContactFields).filter(ContactFields.contact_uuid == contact_uuid).delete() + s.query(ContactFields).filter( + ContactFields.contact_uuid == contact_uuid + ).delete() self._add_field_to_contact(s, contact.uuid, contact_body) return contact_body @@ -169,9 +152,11 @@ def list(self, tenant_uuid, phonebook_id, search=None): if not matching_uuids: return [] - fields = s.query( - ContactFields, - ).filter(ContactFields.contact_uuid.in_(matching_uuids)).all() + fields = ( + s.query(ContactFields) + .filter(ContactFields.contact_uuid.in_(matching_uuids)) + .all() + ) result = defaultdict(dict) for field in fields: result[field.contact_uuid][field.name] = field.value @@ -191,7 +176,9 @@ def _get_contact(self, s, tenant_uuid, phonebook_id, contact_uuid): return contact def _get_phonebook(self, s, tenant_uuid, phonebook_id): - filter_ = and_(Phonebook.id == phonebook_id, Phonebook.tenant_uuid == tenant_uuid) + filter_ = and_( + Phonebook.id == phonebook_id, Phonebook.tenant_uuid == tenant_uuid + ) phonebook = s.query(Phonebook).filter(filter_).first() if not phonebook: raise NoSuchPhonebook(phonebook_id) @@ -240,8 +227,11 @@ def edit(self, tenant_uuid, phonebook_id, phonebook_body): phonebook = self._get_by_tenant_and_id(s, tenant_uuid, phonebook_id) for attribute_name, value in phonebook_body.items(): if not hasattr(phonebook, attribute_name): - raise TypeError('{} has no attribute {}'.format(phonebook.__class__.__name__, - attribute_name)) + raise TypeError( + '{} has no attribute {}'.format( + phonebook.__class__.__name__, attribute_name + ) + ) setattr(phonebook, attribute_name, value) self.flush_or_raise(s, DuplicatedPhonebookException) return self._phonebook_to_dict(phonebook) @@ -251,23 +241,27 @@ def get(self, tenant_uuid, phonebook_id): phonebook = self._get_by_tenant_and_id(s, tenant_uuid, phonebook_id) return self._phonebook_to_dict(phonebook) - def list(self, tenant_uuid, order=None, direction=None, limit=None, offset=None, search=None): + def list( + self, + tenant_uuid, + order=None, + direction=None, + limit=None, + offset=None, + search=None, + ): with self.new_session() as s: phonebooks = self._get_by_tenant( - s, - tenant_uuid, - order, - direction, - limit, - offset, - search, + s, tenant_uuid, order, direction, limit, offset, search ) return [self._phonebook_to_dict(phonebook) for phonebook in phonebooks] def update_tenant(self, old_uuid, phonebook_id, new_uuid): with self.new_session() as s: self._create_tenant(s, new_uuid) - filter_ = and_(Phonebook.id == Phonebook.id, Phonebook.tenant_uuid == old_uuid) + filter_ = and_( + Phonebook.id == Phonebook.id, Phonebook.tenant_uuid == old_uuid + ) phonebook = s.query(Phonebook).filter(filter_).first() phonebook.tenant_uuid = new_uuid s.flush() @@ -281,13 +275,22 @@ def _get_by_tenant(self, s, tenant_uuid, order, direction, limit, offset, search try: order_by_column = getattr(Phonebook, order_by_column_name) except AttributeError: - raise TypeError('{} has no attribute {}'.format(Phonebook.__class__.__name__, - order_by_column_name)) + raise TypeError( + '{} has no attribute {}'.format( + Phonebook.__class__.__name__, order_by_column_name + ) + ) direction = direction or self._default_sort_direction order_by_column_and_direction = getattr(order_by_column, direction)() filter_ = self._new_tenant_filter(s, tenant_uuid, search) - return s.query(Phonebook).filter(filter_).order_by( - order_by_column_and_direction).limit(limit).offset(offset).all() + return ( + s.query(Phonebook) + .filter(filter_) + .order_by(order_by_column_and_direction) + .limit(limit) + .offset(offset) + .all() + ) def _get_by_tenant_and_id(self, s, tenant_uuid, phonebook_id): filter_ = self._new_filter_by_tenant_and_id(s, tenant_uuid, phonebook_id) @@ -304,7 +307,9 @@ def _new_tenant_filter(self, s, tenant_uuid, search): pattern = '%{}%'.format(search) return and_( Phonebook.tenant_uuid == tenant_uuid, - or_(Phonebook.name.ilike(pattern), Phonebook.description.ilike(pattern)), + or_( + Phonebook.name.ilike(pattern), Phonebook.description.ilike(pattern) + ), ) def _new_filter_by_tenant_and_id(self, s, tenant_uuid, phonebook_id): diff --git a/wazo_dird/database/queries/profile.py b/wazo_dird/database/queries/profile.py index 0758c4a3..37518f13 100644 --- a/wazo_dird/database/queries/profile.py +++ b/wazo_dird/database/queries/profile.py @@ -1,26 +1,13 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from sqlalchemy import ( - and_, - exc, - func, - text, -) +from sqlalchemy import and_, exc, func, text from wazo_dird.database import schemas from wazo_dird import exception -from .base import ( - BaseDAO, - extract_constraint_name, -) -from ..import ( - Profile, - ProfileService, - ProfileServiceSource, - Service, -) +from .base import BaseDAO, extract_constraint_name +from .. import Profile, ProfileService, ProfileServiceSource, Service class ProfileCRUD(BaseDAO): @@ -44,7 +31,9 @@ def create(self, body): def delete(self, visible_tenants, profile_uuid): filter_ = self._build_filter(visible_tenants, profile_uuid) with self.new_session() as s: - nb_deleted = s.query(Profile).filter(filter_).delete(synchronize_session=False) + nb_deleted = ( + s.query(Profile).filter(filter_).delete(synchronize_session=False) + ) if not nb_deleted: raise exception.NoSuchProfileAPIException(profile_uuid) @@ -71,7 +60,9 @@ def edit(self, visible_tenants, profile_uuid, body): raise exception.DuplicatedProfileException(body['name']) raise - self._associate_all_services(s, profile.tenant_uuid, profile_uuid, body['services']) + self._associate_all_services( + s, profile.tenant_uuid, profile_uuid, body['services'] + ) def get(self, visible_tenants, profile_uuid): filter_ = self._build_filter(visible_tenants, profile_uuid) @@ -101,20 +92,22 @@ def _associate_all_services(self, session, tenant_uuid, profile_uuid, services): for service_name, config in services.items(): service_uuid = self._create_service(session, service_name) profile_service_uuid = self._create_profile_service( - session, tenant_uuid, profile_uuid, service_uuid, config, + session, tenant_uuid, profile_uuid, service_uuid, config ) for source in config['sources']: source_uuid = str(source.get('uuid')) self._create_profile_service_source( - session, tenant_uuid, profile_service_uuid, source_uuid, + session, tenant_uuid, profile_service_uuid, source_uuid ) def _dissociate_all_services(self, session, profile_uuid): session.query(ProfileService).filter( - ProfileService.profile_uuid == profile_uuid, + ProfileService.profile_uuid == profile_uuid ).delete(synchronize_session=False) - def _list_filter(self, visible_tenants, uuid=None, name=None, search=None, **list_params): + def _list_filter( + self, visible_tenants, uuid=None, name=None, search=None, **list_params + ): filter_ = text('true') if visible_tenants is not None: if not visible_tenants: @@ -130,7 +123,9 @@ def _list_filter(self, visible_tenants, uuid=None, name=None, search=None, **lis return filter_ @staticmethod - def _paginate(query, limit=None, offset=None, order=None, direction=None, **ignored): + def _paginate( + query, limit=None, offset=None, order=None, direction=None, **ignored + ): if order and direction: field = None if order == 'name': @@ -171,7 +166,9 @@ def _create_profile(session, body): return profile.uuid @staticmethod - def _create_profile_service(session, tenant_uuid, profile_uuid, service_uuid, config): + def _create_profile_service( + session, tenant_uuid, profile_uuid, service_uuid, config + ): config = dict(config) config.pop('sources', None) profile_service = ProfileService( @@ -185,7 +182,9 @@ def _create_profile_service(session, tenant_uuid, profile_uuid, service_uuid, co return profile_service.uuid @staticmethod - def _create_profile_service_source(session, tenant_uuid, profile_service_uuid, source_uuid): + def _create_profile_service_source( + session, tenant_uuid, profile_service_uuid, source_uuid + ): if source_uuid is None: raise exception.NoSuchSource(source_uuid) @@ -199,7 +198,10 @@ def _create_profile_service_source(session, tenant_uuid, profile_service_uuid, s try: session.flush() except exc.IntegrityError as e: - if extract_constraint_name(e) == 'dird_profile_service_source_source_uuid_tenant_fkey': + if ( + extract_constraint_name(e) + == 'dird_profile_service_source_source_uuid_tenant_fkey' + ): raise exception.NoSuchSource(source_uuid) raise diff --git a/wazo_dird/database/queries/source.py b/wazo_dird/database/queries/source.py index 5c2ba039..ef2dab4f 100644 --- a/wazo_dird/database/queries/source.py +++ b/wazo_dird/database/queries/source.py @@ -1,17 +1,10 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from sqlalchemy import ( - and_, - exc, - text, -) -from wazo_dird.exception import ( - DuplicatedSourceException, - NoSuchSource, -) +from sqlalchemy import and_, exc, text +from wazo_dird.exception import DuplicatedSourceException, NoSuchSource from .base import BaseDAO -from ..import Source +from .. import Source class SourceCRUD(BaseDAO): @@ -47,7 +40,9 @@ def create(self, backend, source_body): def delete(self, backend, source_uuid, visible_tenants): filter_ = self._multi_tenant_filter(backend, source_uuid, visible_tenants) with self.new_session() as s: - nb_deleted = s.query(Source).filter(filter_).delete(synchronize_session=False) + nb_deleted = ( + s.query(Source).filter(filter_).delete(synchronize_session=False) + ) if not nb_deleted: raise NoSuchSource(source_uuid) @@ -88,7 +83,7 @@ def get_by_uuid(self, uuid): return self._from_db_format(source) def _list_filter( - self, backend, visible_tenants, uuid=None, name=None, search=None, **list_params + self, backend, visible_tenants, uuid=None, name=None, search=None, **list_params ): filter_ = text('true') if visible_tenants is not None: @@ -106,17 +101,16 @@ def _list_filter( return filter_ def _multi_tenant_filter(self, backend, source_uuid, visible_tenants): - filter_ = and_( - Source.backend == backend, - Source.uuid == source_uuid, - ) + filter_ = and_(Source.backend == backend, Source.uuid == source_uuid) if visible_tenants is None: return filter_ return and_(filter_, Source.tenant_uuid.in_(visible_tenants)) - def _paginate(self, query, limit=None, offset=None, order=None, direction=None, **ignored): + def _paginate( + self, query, limit=None, offset=None, order=None, direction=None, **ignored + ): if order and direction: field = None if order == 'name': @@ -142,12 +136,12 @@ def _to_db_format(self, backend, tenant_uuid, uuid=None, *args, **kwargs): @staticmethod def _update_to_db_format( - source, - name, - searched_columns, - first_matched_columns, - format_columns, - **extra_fields + source, + name, + searched_columns, + first_matched_columns, + format_columns, + **extra_fields ): source.name = name source.searched_columns = searched_columns diff --git a/wazo_dird/database/queries/tenant.py b/wazo_dird/database/queries/tenant.py index 09ccc00a..275360ec 100644 --- a/wazo_dird/database/queries/tenant.py +++ b/wazo_dird/database/queries/tenant.py @@ -2,11 +2,10 @@ # SPDX-License-Identifier: GPL-3.0-or-later from .base import BaseDAO -from ..import Tenant +from .. import Tenant class TenantCRUD(BaseDAO): - def delete(self, uuid): with self.new_session() as s: s.query(Tenant).filter(Tenant.uuid == uuid).delete() diff --git a/wazo_dird/database/schemas.py b/wazo_dird/database/schemas.py index e1ccd947..872ae52f 100644 --- a/wazo_dird/database/schemas.py +++ b/wazo_dird/database/schemas.py @@ -25,7 +25,9 @@ class DisplaySchema(BaseSchema): uuid = fields.UUID(dump_only=True) tenant_uuid = fields.UUID(dump_only=True) name = fields.String(validate=Length(min=1, max=512), required=True) - columns = fields.Nested(DisplayColumnSchema, many=True, required=True, validate=Length(min=1)) + columns = fields.Nested( + DisplayColumnSchema, many=True, required=True, validate=Length(min=1) + ) class SourceSchema(BaseSchema): @@ -40,7 +42,6 @@ class ServiceSchema(BaseSchema): class ServiceDictSchema(fields.Nested): - def _serialize(self, value, attr, obj, **kwargs): if value is None: return None diff --git a/wazo_dird/exception.py b/wazo_dird/exception.py index eb5aef04..50409896 100644 --- a/wazo_dird/exception.py +++ b/wazo_dird/exception.py @@ -6,45 +6,37 @@ class OldAPIException(Exception): - def __init__(self, status_code, body): self.status_code = status_code self.body = body class DatabaseServiceUnavailable(Exception): - def __init__(self): super().__init__('Postgresql is unavailable') class NoSuchDisplay(APIException): - def __init__(self, uuid): display_uuid = str(uuid) msg = 'No such display: "{}"'.format(display_uuid) - details = { - 'uuid': display_uuid, - } + details = {'uuid': display_uuid} super().__init__(404, msg, 'unknown-display', details, 'displays') class NoSuchFavorite(ValueError): - def __init__(self, contact_id): message = "No such favorite: {}".format(contact_id) super().__init__(message) class NoSuchPhonebook(ValueError): - def __init__(self, phonebook_id): message = 'No such phonebook: {}'.format(phonebook_id) super().__init__(message) class NoSuchProfile(OldAPIException): - def __init__(self, profile): self.profile = profile status_code = 404 @@ -57,18 +49,14 @@ def __init__(self, profile): class NoSuchProfileAPIException(APIException): - def __init__(self, uuid): profile_uuid = str(uuid) msg = 'No such profile: "{}"'.format(profile_uuid) - details = { - 'uuid': profile_uuid, - } + details = {'uuid': profile_uuid} super().__init__(404, msg, 'unknown-profile', details, 'profiles') class NoSuchUser(OldAPIException): - def __init__(self, user_uuid): status_code = 404 body = { @@ -80,25 +68,20 @@ def __init__(self, user_uuid): class NoSuchContact(ValueError): - def __init__(self, contact_id): message = "No such contact: {}".format(contact_id) super().__init__(message) class NoSuchSource(APIException): - def __init__(self, uuid): source_uuid = str(uuid) msg = 'No such source: "{}"'.format(source_uuid) - details = { - 'uuid': source_uuid, - } + details = {'uuid': source_uuid} super().__init__(404, msg, 'unknown-source', details, 'sources') class NoSuchTenant(ValueError): - def __init__(self, tenant_name): message = 'No such tenant: {}'.format(tenant_name) super().__init__(message) @@ -126,7 +109,6 @@ def __init__(self): class DuplicatedProfileException(APIException): - def __init__(self, name): msg = 'The name "{}" is already used'.format(name) details = {'name': {'constraint_id': 'unique', 'message': msg}} @@ -134,7 +116,6 @@ def __init__(self, name): class DuplicatedSourceException(APIException): - def __init__(self, name): msg = 'The name "{}" is already used'.format(name) details = {'name': {'constraint_id': 'unique', 'message': msg}} @@ -152,7 +133,6 @@ class InvalidArgumentError(Exception): class InvalidConfigError(Exception): - def __init__(self, location_path, msg): super().__init__(location_path, msg) self.location_path = location_path @@ -160,7 +140,6 @@ def __init__(self, location_path, msg): class InvalidPhonebookException(Exception): - def __init__(self, errors): self.errors = errors @@ -174,7 +153,6 @@ class InvalidContactException(Exception): class XiVOConfdError(APIException): - def __init__(self, confd_client, error): super().__init__( status_code=503, @@ -187,5 +165,5 @@ def __init__(self, confd_client, error): 'timeout': confd_client.timeout, }, 'original_error': str(error), - } + }, ) diff --git a/wazo_dird/helpers.py b/wazo_dird/helpers.py index ee20960b..813db1a7 100644 --- a/wazo_dird/helpers.py +++ b/wazo_dird/helpers.py @@ -16,7 +16,6 @@ class DisplayAwareResource: - def build_display(self, profile_config): display = profile_config.get('display', {}) return self._make_display(display) @@ -33,12 +32,12 @@ def _make_display(display): column.get('type'), column.get('default'), column.get('field'), - ) for column in columns + ) + for column in columns ] class RaiseStopper: - def __init__(self, return_on_raise): self.return_on_raise = return_on_raise @@ -51,7 +50,6 @@ def execute(self, function, *args, **kwargs): class BaseService: - def __init__(self, config, source_manager, controller, *args, **kwargs): self._config = config self._source_manager = source_manager @@ -72,7 +70,8 @@ def source_from_profile(self, profile_config): if not result: logger.warning( 'Cannot find "%s" sources for profile %s', - self._service_name, profile_config['name'], + self._service_name, + profile_config['name'], ) return result @@ -82,7 +81,6 @@ def get_service_config(self, profile_config): class _BaseSourceResource(AuthResource): - def __init__(self, backend, service, auth_config): self._service = service self._auth_config = auth_config @@ -90,7 +88,6 @@ def __init__(self, backend, service, auth_config): class SourceList(_BaseSourceResource): - def get(self): list_params, errors = self.list_schema.load(request.args) tenant = Tenant.autodetect() @@ -104,11 +101,7 @@ def get(self): filtered = self._service.count(self._backend, visible_tenants, **list_params) total = self._service.count(self._backend, visible_tenants) - return { - 'total': total, - 'filtered': filtered, - 'items': items, - } + return {'total': total, 'filtered': filtered, 'items': items} def post(self): tenant = Tenant.autodetect() @@ -118,7 +111,6 @@ def post(self): class SourceItem(_BaseSourceResource): - def delete(self, source_uuid): tenant = Tenant.autodetect() visible_tenants = self.get_visible_tenants(tenant.uuid) @@ -141,18 +133,13 @@ def put(self, source_uuid): class BaseBackendView(BaseViewPlugin): - _required_members = [ - 'backend', - 'list_resource', - 'item_resource', - ] + _required_members = ['backend', 'list_resource', 'item_resource'] def __init__(self, *args, **kwargs): members = [getattr(self, name, None) for name in self._required_members] if None in members: msg = '{} should have the following members: {}'.format( - self.__class__.__name__, - self._required_members, + self.__class__.__name__, self._required_members ) raise Exception(msg) diff --git a/wazo_dird/main.py b/wazo_dird/main.py index 226b17eb..2dffc04b 100644 --- a/wazo_dird/main.py +++ b/wazo_dird/main.py @@ -16,9 +16,7 @@ class _PreConfigLogger: - class FlushableBuffer: - def __init__(self): self._msg = [] @@ -56,9 +54,15 @@ def main(argv=None): config = load_config(logger, argv) - xivo_logging.setup_logging(config['log_filename'], config['foreground'], - config['debug'], config['log_level']) - xivo_logging.silence_loggers(['Flask-Cors', 'urllib3', 'stevedore.extension'], logging.WARNING) + xivo_logging.setup_logging( + config['log_filename'], + config['foreground'], + config['debug'], + config['log_level'], + ) + xivo_logging.silence_loggers( + ['Flask-Cors', 'urllib3', 'stevedore.extension'], logging.WARNING + ) if config['user']: change_user(config['user']) diff --git a/wazo_dird/plugin_helpers/confd_client_registry.py b/wazo_dird/plugin_helpers/confd_client_registry.py index 534bd092..5c394fc6 100644 --- a/wazo_dird/plugin_helpers/confd_client_registry.py +++ b/wazo_dird/plugin_helpers/confd_client_registry.py @@ -17,7 +17,6 @@ class _Registry: - def __init__(self): self._clients = {} self._clients_lock = Lock() @@ -44,7 +43,9 @@ def _add_client(self, source_config): # File must be readable by wazo-dird key_file = parse_config_file(auth_config.pop('key_file')) if not key_file: - logger.info('failed to load key file for source %s', source_config['name']) + logger.info( + 'failed to load key file for source %s', source_config['name'] + ) return auth_config['username'] = key_file['service_id'] auth_config['password'] = key_file['service_key'] diff --git a/wazo_dird/plugin_manager.py b/wazo_dird/plugin_manager.py index e21f6e97..1989b4c2 100644 --- a/wazo_dird/plugin_manager.py +++ b/wazo_dird/plugin_manager.py @@ -24,9 +24,7 @@ def load_services(config, enabled_services, source_manager, bus, controller): } services_extension_manager, services = _load_plugins( - 'wazo_dird.services', - enabled_services, - dependencies, + 'wazo_dird.services', enabled_services, dependencies ) return services @@ -55,7 +53,9 @@ def load_views(config, enabled_views, services, auth_client, status_aggregator): 'api': rest_api.api, 'status_aggregator': status_aggregator, } - views_extension_manager, views = _load_plugins('wazo_dird.views', enabled_views, dependencies) + views_extension_manager, views = _load_plugins( + 'wazo_dird.views', enabled_views, dependencies + ) return views @@ -72,7 +72,7 @@ def _load_plugins(namespace, names, dependencies): name_order=True, on_load_failure_callback=plugin_helpers.on_load_failure, on_missing_entrypoints_callback=plugin_helpers.on_missing_entrypoints, - invoke_on_load=True + invoke_on_load=True, ) def _load_plugin(ext, *args, **kwargs): diff --git a/wazo_dird/plugins/api/http.py b/wazo_dird/plugins/api/http.py index ae867fe3..4bb362b8 100644 --- a/wazo_dird/plugins/api/http.py +++ b/wazo_dird/plugins/api/http.py @@ -23,7 +23,9 @@ def get(self): for module in iter_entry_points(group=self.api_entry_point): try: plugin_package = module.module_name.rsplit('.', 1)[0] - spec = yaml.safe_load(resource_string(plugin_package, self.api_filename)) + spec = yaml.safe_load( + resource_string(plugin_package, self.api_filename) + ) if not spec: logger.debug('plugin has no API spec: %s', plugin_package) else: @@ -31,13 +33,17 @@ def get(self): except ImportError: logger.debug('failed to import %s', plugin_package) except IOError: - logger.debug('API spec for module "%s" does not exist', module.module_name) + logger.debug( + 'API spec for module "%s" does not exist', module.module_name + ) except IndexError: - logger.debug('Could not find API spec from module "%s"', module.module_name) + logger.debug( + 'Could not find API spec from module "%s"', module.module_name + ) except NotImplementedError: logger.debug( 'Are you sure you have an __init__ file in your module "%s"?', - module.module_name + module.module_name, ) api_spec = ChainMap(*specs) @@ -45,7 +51,5 @@ def get(self): return {'error': "API spec does not exist"}, 404 return make_response( - yaml.dump(dict(api_spec)), - 200, - {'Content-Type': 'application/x-yaml'}, + yaml.dump(dict(api_spec)), 200, {'Content-Type': 'application/x-yaml'} ) diff --git a/wazo_dird/plugins/api/plugin.py b/wazo_dird/plugins/api/plugin.py index fd45bbe2..f1569d04 100644 --- a/wazo_dird/plugins/api/plugin.py +++ b/wazo_dird/plugins/api/plugin.py @@ -7,7 +7,6 @@ class ApiViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] api.add_resource(http.ApiResource, '/api/api.yml') diff --git a/wazo_dird/plugins/backends/http.py b/wazo_dird/plugins/backends/http.py index 909a59da..eec2570d 100644 --- a/wazo_dird/plugins/backends/http.py +++ b/wazo_dird/plugins/backends/http.py @@ -10,7 +10,6 @@ class Backends(LegacyAuthResource): - def __init__(self, service): self._service = service @@ -22,8 +21,4 @@ def get(self): filtered = self._service.count(**list_params) total = self._service.count() - return { - 'total': total, - 'filtered': filtered, - 'items': backends, - } + return {'total': total, 'filtered': filtered, 'items': backends} diff --git a/wazo_dird/plugins/backends/plugin.py b/wazo_dird/plugins/backends/plugin.py index b3801661..e4d9f173 100644 --- a/wazo_dird/plugins/backends/plugin.py +++ b/wazo_dird/plugins/backends/plugin.py @@ -8,13 +8,10 @@ class BackendsViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] backend_service = service.BackendService(dependencies['config']) api.add_resource( - http.Backends, - '/backends', - resource_class_args=(backend_service,), + http.Backends, '/backends', resource_class_args=(backend_service,) ) diff --git a/wazo_dird/plugins/backends/service.py b/wazo_dird/plugins/backends/service.py index de447082..ed2cd3d8 100644 --- a/wazo_dird/plugins/backends/service.py +++ b/wazo_dird/plugins/backends/service.py @@ -16,8 +16,10 @@ def __init__(self, config): continue configured_backends.add(backend_name) - installed_backends = set(module.name for module in - iter_entry_points(group=self._backend_entry_points)) + installed_backends = set( + module.name + for module in iter_entry_points(group=self._backend_entry_points) + ) self._backends = [ {'name': backend} for backend in configured_backends & installed_backends @@ -64,7 +66,7 @@ def _paginate(backends, limit=None, offset=None, **ignored): offset = 0 or offset if limit is not None: - return backends[offset:limit+offset] + return backends[offset : limit + offset] return backends[offset:] diff --git a/wazo_dird/plugins/base_plugins.py b/wazo_dird/plugins/base_plugins.py index 763ad6e0..8465baf8 100644 --- a/wazo_dird/plugins/base_plugins.py +++ b/wazo_dird/plugins/base_plugins.py @@ -24,7 +24,6 @@ def unload(self): class BaseViewPlugin(metaclass=abc.ABCMeta): - @abc.abstractmethod def load(self, dependencies): ''' diff --git a/wazo_dird/plugins/cleanup_service/plugin.py b/wazo_dird/plugins/cleanup_service/plugin.py index e43fba72..1c54c8b1 100644 --- a/wazo_dird/plugins/cleanup_service/plugin.py +++ b/wazo_dird/plugins/cleanup_service/plugin.py @@ -16,7 +16,6 @@ class StorageCleanupServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -32,9 +31,9 @@ class _StorageCleanupService: _routing_key = 'config.user.deleted' def __init__(self, bus): - queue = kombu.Queue(exchange=self._exchange, - routing_key=self._routing_key, - exclusive=True) + queue = kombu.Queue( + exchange=self._exchange, routing_key=self._routing_key, exclusive=True + ) bus.add_consumer(queue, self._on_user_deleted_event) # executed in the consumer thread diff --git a/wazo_dird/plugins/conference_backend/http.py b/wazo_dird/plugins/conference_backend/http.py index f2997929..2c2605d6 100644 --- a/wazo_dird/plugins/conference_backend/http.py +++ b/wazo_dird/plugins/conference_backend/http.py @@ -5,10 +5,7 @@ from xivo.tenant_flask_helpers import Tenant from wazo_dird import exception -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) +from wazo_dird.helpers import SourceItem, SourceList from wazo_dird.auth import required_acl from wazo_dird.rest_api import AuthResource from wazo_dird.plugin_helpers.confd_client_registry import registry @@ -55,7 +52,6 @@ def put(self, source_uuid): class ConferenceContactList(AuthResource): - def __init__(self, source_service): self._source_service = source_service @@ -64,7 +60,9 @@ def get(self, source_uuid): tenant_uuid = Tenant.autodetect().uuid visible_tenants = self.get_visible_tenants(tenant_uuid) list_params = contact_list_param_schema.load(request.args).data - source_config = self._source_service.get('conference', source_uuid, visible_tenants) + source_config = self._source_service.get( + 'conference', source_uuid, visible_tenants + ) confd = registry.get(source_config) try: diff --git a/wazo_dird/plugins/conference_backend/plugin.py b/wazo_dird/plugins/conference_backend/plugin.py index 6601558e..368716e9 100644 --- a/wazo_dird/plugins/conference_backend/plugin.py +++ b/wazo_dird/plugins/conference_backend/plugin.py @@ -5,13 +5,8 @@ from requests import HTTPError -from wazo_dird import ( - BaseSourcePlugin, - make_result_class, -) -from wazo_dird.helpers import ( - BaseBackendView, -) +from wazo_dird import BaseSourcePlugin, make_result_class +from wazo_dird.helpers import BaseBackendView from wazo_dird.plugin_helpers.confd_client_registry import registry from . import http @@ -42,7 +37,6 @@ def unload(self): class ConferencePlugin(BaseSourcePlugin): - def __init__(self): self._client = None self._uuid = None @@ -73,7 +67,9 @@ def list(self, unique_ids, args=None): def search(self, term, profile=None, args=None): lowered_term = term.lower() contacts = self._fetch_contacts() - matching_contacts = (c for c in contacts if self._search_filter(lowered_term, c)) + matching_contacts = ( + c for c in contacts if self._search_filter(lowered_term, c) + ) return [self._SourceResult(c) for c in matching_contacts] def first_match(self, term, args=None): diff --git a/wazo_dird/plugins/conference_backend/tests/test_schemas.py b/wazo_dird/plugins/conference_backend/tests/test_schemas.py index 0e09b918..1bac4b6e 100644 --- a/wazo_dird/plugins/conference_backend/tests/test_schemas.py +++ b/wazo_dird/plugins/conference_backend/tests/test_schemas.py @@ -3,19 +3,12 @@ from unittest import TestCase -from hamcrest import ( - assert_that, - contains, - contains_inanyorder, - empty, - has_entries, -) +from hamcrest import assert_that, contains, contains_inanyorder, empty, has_entries from ..schemas import contact_list_schema class TestContactSchema(TestCase): - def test_dump(self): raw = [ { @@ -29,12 +22,14 @@ def test_dump(self): 'exten': '4001', 'context': 'from-extern', 'id': 77, - 'links': [{'rel': 'extensions', 'href': '.../extensions/77'}], - }, + 'links': [ + {'rel': 'extensions', 'href': '.../extensions/77'} + ], + } ], 'id': 14, - 'links': [{'rel': 'incalls', 'href': '.../incalls/14'}] - }, + 'links': [{'rel': 'incalls', 'href': '.../incalls/14'}], + } ], }, { @@ -46,7 +41,7 @@ def test_dump(self): 'context': 'inside', 'id': 57, 'links': [{'rel': 'extensions', 'href': '.../extensions/57'}], - }, + } ], 'incalls': [ { @@ -55,29 +50,34 @@ def test_dump(self): 'exten': '1009', 'context': 'from-extern', 'id': 76, - 'links': [{'rel': 'extensions', 'href': '.../extensions/76'}], - }, + 'links': [ + {'rel': 'extensions', 'href': '.../extensions/76'} + ], + } ], 'id': 13, 'links': [{'rel': 'incalls', 'href': '.../incalls/13'}], - }, + } ], }, ] result = contact_list_schema.dump(raw).data - assert_that(result, contains_inanyorder( - has_entries( - id=3, - name='minimal', - extensions=empty(), - incalls=contains(has_entries(exten='4001')), - ), - has_entries( - id=1, - name='test', - extensions=contains(has_entries(exten='4001')), - incalls=contains(has_entries(exten='1009')), + assert_that( + result, + contains_inanyorder( + has_entries( + id=3, + name='minimal', + extensions=empty(), + incalls=contains(has_entries(exten='4001')), + ), + has_entries( + id=1, + name='test', + extensions=contains(has_entries(exten='4001')), + incalls=contains(has_entries(exten='1009')), + ), ), - )) + ) diff --git a/wazo_dird/plugins/config/plugin.py b/wazo_dird/plugins/config/plugin.py index 479a7470..9d073580 100644 --- a/wazo_dird/plugins/config/plugin.py +++ b/wazo_dird/plugins/config/plugin.py @@ -20,7 +20,8 @@ def load(self, dependencies): config_service = dependencies['services'].get('config') if not config_service: logger.info( - 'failed to load the %s config service is disabled', self.__class__.__name__, + 'failed to load the %s config service is disabled', + self.__class__.__name__, ) return diff --git a/wazo_dird/plugins/config_service/plugin.py b/wazo_dird/plugins/config_service/plugin.py index ea807c28..e80aa88d 100644 --- a/wazo_dird/plugins/config_service/plugin.py +++ b/wazo_dird/plugins/config_service/plugin.py @@ -14,7 +14,12 @@ DEFAULT_DISPLAY_COLUMNS = [ {'field': 'name', 'title': 'Nom', 'type': 'name'}, - {'field': 'phone', 'title': "Num\xE9ro", 'type': 'number', 'number_display': '{name}'}, + { + 'field': 'phone', + 'title': "Num\xE9ro", + 'type': 'number', + 'number_display': '{name}', + }, { 'field': 'phone_mobile', 'title': 'Mobile', @@ -40,9 +45,7 @@ 'verify_certificate': '/usr/share/xivo-certs/server.crt', 'version': '1.1', }, - 'format_columns': { - 'phone': '{extensions[0]}', - }, + 'format_columns': {'phone': '{extensions[0]}'}, 'searched_columns': ['name', 'extensions', 'incalls'], 'first_matched_columns': [], } @@ -72,10 +75,7 @@ 'verify_certificate': '/usr/share/xivo-certs/server.crt', 'version': '1.1', }, - 'format_columns': { - 'phone': '{exten}', - 'name': '{firstname} {lastname}', - }, + 'format_columns': {'phone': '{exten}', 'name': '{firstname} {lastname}'}, 'searched_columns': ['firstname', 'lastname', 'exten'], 'first_matched_columns': [], } @@ -100,7 +100,6 @@ class ConfigServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -200,7 +199,8 @@ def _auto_create_display(self, tenant_uuid, name): ) logger.info( 'display %s auto created for tenant %s', - display['uuid'], display['tenant_uuid'], + display['uuid'], + display['tenant_uuid'], ) return display except Exception as e: @@ -215,10 +215,7 @@ def _auto_create_profile(self, tenant_uuid, name, display, sources): 'services': { 'lookup': {'sources': sources}, 'favorites': {'sources': sources}, - 'reverse': { - 'sources': sources, - 'timeout': 0.5, - }, + 'reverse': {'sources': sources, 'timeout': 0.5}, }, } diff --git a/wazo_dird/plugins/config_service/tests/test_config_service.py b/wazo_dird/plugins/config_service/tests/test_config_service.py index 8d405a71..9a04cc49 100644 --- a/wazo_dird/plugins/config_service/tests/test_config_service.py +++ b/wazo_dird/plugins/config_service/tests/test_config_service.py @@ -3,20 +3,13 @@ import unittest -from hamcrest import ( - assert_that, - equal_to, -) -from mock import ( - Mock, - sentinel as s, -) +from hamcrest import assert_that, equal_to +from mock import Mock, sentinel as s from ..plugin import Service class TestConfigService(unittest.TestCase): - def test_that_get_current_config_returns_the_config(self): service = Service(s.original_config, Mock(), s.controller) diff --git a/wazo_dird/plugins/csv_backend/http.py b/wazo_dird/plugins/csv_backend/http.py index 341ecefa..a2d14d41 100644 --- a/wazo_dird/plugins/csv_backend/http.py +++ b/wazo_dird/plugins/csv_backend/http.py @@ -3,16 +3,9 @@ from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) - -from .schemas import ( - list_schema, - source_schema, - source_list_schema, -) +from wazo_dird.helpers import SourceItem, SourceList + +from .schemas import list_schema, source_schema, source_list_schema class CSVList(SourceList): diff --git a/wazo_dird/plugins/csv_backend/plugin.py b/wazo_dird/plugins/csv_backend/plugin.py index f0b4b1a8..e20d9a4e 100644 --- a/wazo_dird/plugins/csv_backend/plugin.py +++ b/wazo_dird/plugins/csv_backend/plugin.py @@ -48,7 +48,7 @@ def load(self, args): backend, self._name, self._config.get(self.UNIQUE_COLUMN, None), - self._config.get(self.FORMAT_COLUMNS, {}) + self._config.get(self.FORMAT_COLUMNS, {}), ) def name(self): @@ -58,7 +58,11 @@ def search(self, term, args=None): if self.SEARCHED_COLUMNS not in self._config: return [] - fn = partial(self._low_case_match_entry, term.lower(), self._config[self.SEARCHED_COLUMNS]) + fn = partial( + self._low_case_match_entry, + term.lower(), + self._config[self.SEARCHED_COLUMNS], + ) return self._list_from_predicate(fn) def first_match(self, term, args=None): @@ -66,7 +70,9 @@ def first_match(self, term, args=None): return None for entry in self._content: - if self._exact_match_entry(term, self._config[self.FIRST_MATCHED_COLUMNS], entry): + if self._exact_match_entry( + term, self._config[self.FIRST_MATCHED_COLUMNS], entry + ): return self._SourceResult(entry) return None diff --git a/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py b/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py index a0566b06..bdbec6bb 100644 --- a/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py +++ b/wazo_dird/plugins/csv_backend/tests/test_csv_plugin.py @@ -26,15 +26,16 @@ SourceResult = make_result_class('test-csv', 'my_directory', unique_column='clientno') -alice = {'clientno': '1', - 'firstname': 'Alice', - 'lastname': 'AAA', - 'number': '5555555555', - 'age': '20'} +alice = { + 'clientno': '1', + 'firstname': 'Alice', + 'lastname': 'AAA', + 'number': '5555555555', + 'age': '20', +} class BaseCSVTestDirectory(unittest.TestCase): - @classmethod def setUpClass(cls): cls.fd, cls.fname = tempfile.mkstemp() @@ -75,16 +76,20 @@ class TestCsvDirectorySource(BaseCSVTestDirectory): def setUp(self): self.name = 'my_directory' - self.bob = {'clientno': '2', - 'firstname': 'Bob', - 'lastname': 'BBB', - 'number': '5555551234', - 'age': '21'} - self.charles = {'clientno': '3', - 'firstname': 'Charles', - 'lastname': 'CCC', - 'number': '5555556666', - 'age': '22'} + self.bob = { + 'clientno': '2', + 'firstname': 'Bob', + 'lastname': 'BBB', + 'number': '5555551234', + 'age': '21', + } + self.charles = { + 'clientno': '3', + 'firstname': 'Charles', + 'lastname': 'CCC', + 'number': '5555556666', + 'age': '22', + } self.source = CSVPlugin() self.alice_result = SourceResult(alice) self.charles_result = SourceResult(self.charles) @@ -109,14 +114,13 @@ def test_load_invalid_file_does_not_crash(self): assert_that(result, contains()) def test_load_file(self): - config = { - 'file': self.fname, - 'name': self.name, - } + config = {'file': self.fname, 'name': self.name} self.source.load({'config': config}) - assert_that(self.source._content, contains_inanyorder(alice, self.bob, self.charles)) + assert_that( + self.source._content, contains_inanyorder(alice, self.bob, self.charles) + ) def test_search(self): config = { @@ -146,10 +150,7 @@ def test_search_not_search_column(self): assert_that(results, contains()) def test_search_no_search_column(self): - config = { - 'file': self.fname, - 'name': 'my_dir', - } + config = {'file': self.fname, 'name': 'my_dir'} self.source.load({'config': config}) @@ -200,10 +201,7 @@ def test_first_match_when_no_match(self): assert_that(results, equal_to(None)) def test_list_no_unique(self): - config = { - 'file': self.fname, - 'name': 'my_dir', - } + config = {'file': self.fname, 'name': 'my_dir'} self.source.load({'config': config}) @@ -212,11 +210,7 @@ def test_list_no_unique(self): assert_that(results, contains()) def test_list_with_unique_column_but_empty_uids(self): - config = { - 'file': self.fname, - 'unique_column': 'clientno', - 'name': self.name, - } + config = {'file': self.fname, 'unique_column': 'clientno', 'name': self.name} self.source.load({'config': config}) @@ -225,11 +219,7 @@ def test_list_with_unique_column_but_empty_uids(self): assert_that(results, contains()) def test_list_with_unique_column(self): - config = { - 'file': self.fname, - 'unique_column': 'clientno', - 'name': self.name, - } + config = {'file': self.fname, 'unique_column': 'clientno', 'name': self.name} self.source.load({'config': config}) @@ -246,32 +236,24 @@ def test_row_to_dict(self): assert_that(result, equal_to({'one': 1, 'two': 2, 'three': 3})) def test_is_in_unique_ids(self): - config = { - 'file': self.fname, - 'unique_column': 'clientno', - 'name': 'my_dir', - } + config = {'file': self.fname, 'unique_column': 'clientno', 'name': 'my_dir'} self.source.load({'config': config}) result = self.source._is_in_unique_ids( - ['12'], {'firstname': 'Alice', 'lastname': 'AAA', 'clientno': '12'}, + ['12'], {'firstname': 'Alice', 'lastname': 'AAA', 'clientno': '12'} ) assert_that(result, equal_to(True)) result = self.source._is_in_unique_ids( - ['12'], {'firstname': 'Bob', 'lastname': 'BBB', 'clientno': '55'}, + ['12'], {'firstname': 'Bob', 'lastname': 'BBB', 'clientno': '55'} ) assert_that(result, equal_to(False)) def test_low_case_match_entry(self): - config = { - 'file': self.fname, - 'unique_column': 'clientno', - 'name': 'my_dir', - } + config = {'file': self.fname, 'unique_column': 'clientno', 'name': 'my_dir'} term = 'ice' columns = ['firstname', 'lastname'] @@ -283,11 +265,7 @@ def test_low_case_match_entry(self): assert_that(result, equal_to(True)) def test_low_case_match_entry_broken_config(self): - config = { - 'file': self.fname, - 'unique_column': 'clientno', - 'name': 'my_dir', - } + config = {'file': self.fname, 'unique_column': 'clientno', 'name': 'my_dir'} term = 'ice' columns = [None, 'firstname', 'lastname'] diff --git a/wazo_dird/plugins/csv_ws_backend/http.py b/wazo_dird/plugins/csv_ws_backend/http.py index 01b236c8..0d984d5b 100644 --- a/wazo_dird/plugins/csv_ws_backend/http.py +++ b/wazo_dird/plugins/csv_ws_backend/http.py @@ -3,16 +3,9 @@ from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) - -from .schemas import ( - list_schema, - source_schema, - source_list_schema, -) +from wazo_dird.helpers import SourceItem, SourceList + +from .schemas import list_schema, source_schema, source_list_schema class CSVWSList(SourceList): diff --git a/wazo_dird/plugins/csv_ws_backend/plugin.py b/wazo_dird/plugins/csv_ws_backend/plugin.py index ff6ba019..893e563c 100644 --- a/wazo_dird/plugins/csv_ws_backend/plugin.py +++ b/wazo_dird/plugins/csv_ws_backend/plugin.py @@ -23,14 +23,15 @@ class CSVWSView(BaseBackendView): class CSVWSPlugin(BaseSourcePlugin): - def load(self, config): logger.debug('Loading with %s', config) self._name = config['config']['name'] self._list_url = config['config'].get('list_url') self._lookup_url = config['config']['lookup_url'] - self._first_matched_columns = config['config'].get(self.FIRST_MATCHED_COLUMNS, []) + self._first_matched_columns = config['config'].get( + self.FIRST_MATCHED_COLUMNS, [] + ) self._searched_columns = config['config'].get(self.SEARCHED_COLUMNS, []) self._unique_column = config['config'].get(self.UNIQUE_COLUMN) backend = config['config'].get('backend', '') @@ -38,7 +39,8 @@ def load(self, config): backend, config['config']['name'], self._unique_column, - config['config'].get(self.FORMAT_COLUMNS, {})) + config['config'].get(self.FORMAT_COLUMNS, {}), + ) self._timeout = config['config'].get('timeout', 10) self._delimiter = config['config'].get('delimiter', ',') self._verify_certificate = config['config'].get('verify_certificate', True) @@ -51,7 +53,10 @@ def search(self, term, args=None): try: response = requests.get( - url, params=params, timeout=self._timeout, verify=self._verify_certificate, + url, + params=params, + timeout=self._timeout, + verify=self._verify_certificate, ) except RequestException as e: logger.error('Error connecting to %s: %s', url, e) @@ -61,9 +66,11 @@ def search(self, term, args=None): logger.debug('GET %s %s', url, response.status_code) return [] - return [self._SourceResult(result) - for result in self._reader.from_text(response.text) - if result] + return [ + self._SourceResult(result) + for result in self._reader.from_text(response.text) + if result + ] def first_match(self, term, args=None): logger.debug('First matching CSV WS `%s` with `%s`', self._name, term) @@ -72,7 +79,10 @@ def first_match(self, term, args=None): try: response = requests.get( - url, params=params, timeout=self._timeout, verify=self._verify_certificate, + url, + params=params, + timeout=self._timeout, + verify=self._verify_certificate, ) except RequestException as e: logger.error('Error connecting to %s: %s', url, e) @@ -89,13 +99,15 @@ def first_match(self, term, args=None): return None def list(self, source_entry_ids, args=None): - logger.debug('Listing contacts %s from CSV WS `%s`', source_entry_ids, self._name) + logger.debug( + 'Listing contacts %s from CSV WS `%s`', source_entry_ids, self._name + ) if not (self._unique_column and self._list_url): return [] try: response = requests.get( - self._list_url, timeout=self._timeout, verify=self._verify_certificate, + self._list_url, timeout=self._timeout, verify=self._verify_certificate ) except RequestException as e: logger.error('Error connecting to %s: %s', self._list_url, e) @@ -104,13 +116,14 @@ def list(self, source_entry_ids, args=None): if response.status_code != 200: return [] - return [self._SourceResult(result) - for result in self._reader.from_text(response.text) - if result.get(self._unique_column) in source_entry_ids] + return [ + self._SourceResult(result) + for result in self._reader.from_text(response.text) + if result.get(self._unique_column) in source_entry_ids + ] class _CSVReader: - def __init__(self, delimiter): self._delimiter = delimiter diff --git a/wazo_dird/plugins/csv_ws_backend/schemas.py b/wazo_dird/plugins/csv_ws_backend/schemas.py index 9dbc6557..707150a4 100644 --- a/wazo_dird/plugins/csv_ws_backend/schemas.py +++ b/wazo_dird/plugins/csv_ws_backend/schemas.py @@ -2,15 +2,9 @@ # SPDX-License-Identifier: GPL-3.0-or-later from xivo.mallow import fields -from xivo.mallow.validate import ( - Length, - Range, -) +from xivo.mallow.validate import Length, Range from xivo.mallow_helpers import ListSchema as _ListSchema -from wazo_dird.schemas import ( - BaseSourceSchema, - VerifyCertificateField, -) +from wazo_dird.schemas import BaseSourceSchema, VerifyCertificateField class SourceSchema(BaseSourceSchema): diff --git a/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py b/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py index e560ea9f..d739fa06 100644 --- a/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py +++ b/wazo_dird/plugins/csv_ws_backend/tests/test_csv_ws.py @@ -11,7 +11,6 @@ class TestCSVWSPlugin(unittest.TestCase): - def test_that_a_missing_lookup_url_fails_on_load(self): source = CSVWSPlugin() @@ -20,13 +19,14 @@ def test_that_a_missing_lookup_url_fails_on_load(self): @patch('wazo_dird.plugins.csv_ws_backend.plugin.requests') def test_that_search_queries_the_lookup_url(self, mocked_requests): lookup_url = 'http://example.com:8000/ws' - config = {'config': {'lookup_url': lookup_url, - 'name': 'my-ws-source', - 'timeout': s.timeout, - 'searched_columns': [ - 'firstname', - 'lastname', - ]}} + config = { + 'config': { + 'lookup_url': lookup_url, + 'name': 'my-ws-source', + 'timeout': s.timeout, + 'searched_columns': ['firstname', 'lastname'], + } + } term = 'dédé' expected_params = {'firstname': 'dédé', 'lastname': 'dédé'} @@ -36,20 +36,21 @@ def test_that_search_queries_the_lookup_url(self, mocked_requests): source.search(term) mocked_requests.get.assert_called_once_with( - lookup_url, params=expected_params, timeout=s.timeout, verify=True, + lookup_url, params=expected_params, timeout=s.timeout, verify=True ) @patch('wazo_dird.plugins.csv_ws_backend.plugin.requests') def test_that_first_match_queries_the_lookup_url(self, mocked_requests): lookup_url = 'http://example.com:8000/ws' - config = {'config': {'lookup_url': lookup_url, - 'name': 'my-ws-source', - 'timeout': s.timeout, - 'searched_columns': [ - 'firstname', - 'lastname', - ], - 'first_matched_columns': ['exten']}} + config = { + 'config': { + 'lookup_url': lookup_url, + 'name': 'my-ws-source', + 'timeout': s.timeout, + 'searched_columns': ['firstname', 'lastname'], + 'first_matched_columns': ['exten'], + } + } term = '1234' expected_params = {'exten': '1234'} @@ -59,13 +60,17 @@ def test_that_first_match_queries_the_lookup_url(self, mocked_requests): source.first_match(term) mocked_requests.get.assert_called_once_with( - lookup_url, params=expected_params, timeout=s.timeout, verify=True, + lookup_url, params=expected_params, timeout=s.timeout, verify=True ) def test_that_list_returns_an_empty_list_if_no_unique_column(self): - config = {'config': {'lookup_url': 'the_lookup_url', - 'name': 'my-ws-source', - 'timeout': s.timeout}} + config = { + 'config': { + 'lookup_url': 'the_lookup_url', + 'name': 'my-ws-source', + 'timeout': s.timeout, + } + } source = CSVWSPlugin() source.load(config) @@ -75,10 +80,14 @@ def test_that_list_returns_an_empty_list_if_no_unique_column(self): assert_that(result, is_(empty())) def test_that_list_returns_an_empty_list_if_no_list_url(self): - config = {'config': {'lookup_url': 'the_lookup_url', - 'unique_column': 'id', - 'name': 'my-ws-source', - 'timeout': s.timeout}} + config = { + 'config': { + 'lookup_url': 'the_lookup_url', + 'unique_column': 'id', + 'name': 'my-ws-source', + 'timeout': s.timeout, + } + } source = CSVWSPlugin() source.load(config) @@ -89,15 +98,21 @@ def test_that_list_returns_an_empty_list_if_no_list_url(self): @patch('wazo_dird.plugins.csv_ws_backend.plugin.requests') def test_that_list_queries_the_list_url(self, mocked_requests): - config = {'config': {'list_url': 'the_list_url', - 'lookup_url': 'the_lookup_url', - 'unique_column': 'id', - 'name': 'my-ws-source', - 'timeout': s.timeout}} + config = { + 'config': { + 'list_url': 'the_list_url', + 'lookup_url': 'the_lookup_url', + 'unique_column': 'id', + 'name': 'my-ws-source', + 'timeout': s.timeout, + } + } source = CSVWSPlugin() source.load(config) source.list([1, 2, 3]) - mocked_requests.get.assert_called_once_with('the_list_url', timeout=s.timeout, verify=True) + mocked_requests.get.assert_called_once_with( + 'the_list_url', timeout=s.timeout, verify=True + ) diff --git a/wazo_dird/plugins/default_json/http.py b/wazo_dird/plugins/default_json/http.py index b84d1080..95782185 100644 --- a/wazo_dird/plugins/default_json/http.py +++ b/wazo_dird/plugins/default_json/http.py @@ -18,7 +18,9 @@ logger = logging.getLogger(__name__) parser = reqparse.RequestParser() -parser.add_argument('term', type=str, required=True, help='term is missing', location='args') +parser.add_argument( + 'term', type=str, required=True, help='term is missing', location='args' +) parser_reverse = reqparse.RequestParser() parser_reverse.add_argument('exten', type=str, required=True, location='args') @@ -26,20 +28,18 @@ def _error(code, msg): logger.error(msg) - return {'reason': [msg], - 'timestamp': [time()], - 'status_code': code}, code + return {'reason': [msg], 'timestamp': [time()], 'status_code': code}, code class DisabledFavoriteService: - def favorite_ids(self, profile, xivo_user_uuid): return [] class Lookup(LegacyAuthResource, DisplayAwareResource): - - def __init__(self, lookup_service, favorite_service, display_service, profile_service): + def __init__( + self, lookup_service, favorite_service, display_service, profile_service + ): self.lookup_service = lookup_service self.favorite_service = favorite_service self.display_service = display_service @@ -64,13 +64,11 @@ def get(self, profile): xivo_user_uuid = token_infos['xivo_user_uuid'] raw_results = self.lookup_service.lookup( - profile_config, - tenant.uuid, - term, - xivo_user_uuid, - token=token, + profile_config, tenant.uuid, term, xivo_user_uuid, token=token ) - favorites = self.favorite_service.favorite_ids(profile_config, xivo_user_uuid).by_name + favorites = self.favorite_service.favorite_ids( + profile_config, xivo_user_uuid + ).by_name formatter = _ResultFormatter(display) response = formatter.format_results(raw_results, favorites) @@ -80,7 +78,6 @@ def get(self, profile): class Reverse(LegacyAuthResource): - def __init__(self, reverse_service, profile_service): self.reverse_service = reverse_service self.profile_service = profile_service @@ -100,16 +97,10 @@ def get(self, profile, xivo_user_uuid): logger.info('Reverse for %s with profile %s', exten, profile) raw_result = self.reverse_service.reverse( - profile_config, - exten, - profile, - xivo_user_uuid=xivo_user_uuid, - token=token) + profile_config, exten, profile, xivo_user_uuid=xivo_user_uuid, token=token + ) - response = {'display': None, - 'exten': exten, - 'fields': {}, - 'source': None} + response = {'display': None, 'exten': exten, 'fields': {}, 'source': None} if raw_result is not None: response['display'] = raw_result.fields.get('reverse') @@ -120,7 +111,6 @@ def get(self, profile, xivo_user_uuid): class FavoritesRead(LegacyAuthResource, DisplayAwareResource): - def __init__(self, favorites_service, display_service, profile_service): self.favorites_service = favorites_service self.display_service = display_service @@ -141,9 +131,7 @@ def get(self, profile): try: raw_results = self.favorites_service.favorites( - profile_config, - token_infos['xivo_user_uuid'], - token, + profile_config, token_infos['xivo_user_uuid'], token ) except self.favorites_service.NoSuchProfileException as e: return _error(404, str(e)) @@ -153,7 +141,6 @@ def get(self, profile): class FavoritesWrite(LegacyAuthResource): - def __init__(self, favorites_service): self.favorites_service = favorites_service @@ -165,10 +152,7 @@ def put(self, directory, contact): tenant = Tenant.autodetect() try: self.favorites_service.new_favorite( - tenant.uuid, - directory, - contact, - token_infos['xivo_user_uuid'], + tenant.uuid, directory, contact, token_infos['xivo_user_uuid'] ) except self.favorites_service.DuplicatedFavoriteException: return _error(409, 'Adding this favorite would create a duplicate') @@ -184,20 +168,20 @@ def delete(self, directory, contact): tenant = Tenant.autodetect() try: self.favorites_service.remove_favorite( - tenant.uuid, - directory, - contact, - token_infos['xivo_user_uuid'], + tenant.uuid, directory, contact, token_infos['xivo_user_uuid'] ) return '', 204 - except (self.favorites_service.NoSuchFavoriteException, - self.favorites_service.NoSuchSourceException) as e: + except ( + self.favorites_service.NoSuchFavoriteException, + self.favorites_service.NoSuchSourceException, + ) as e: return _error(404, str(e)) class Personal(LegacyAuthResource, DisplayAwareResource): - - def __init__(self, personal_service, favorite_service, display_service, profile_service): + def __init__( + self, personal_service, favorite_service, display_service, profile_service + ): self.personal_service = personal_service self.favorite_service = favorite_service or DisabledFavoriteService() self.display_service = display_service @@ -217,14 +201,12 @@ def get(self, profile): return e.body, e.status_code raw_results = self.personal_service.list_contacts( - tenant.uuid, - token_infos['xivo_user_uuid'], + tenant.uuid, token_infos['xivo_user_uuid'] ) try: favorites = self.favorite_service.favorite_ids( - profile_config, - token_infos['xivo_user_uuid'], + profile_config, token_infos['xivo_user_uuid'] ).by_name except self.favorite_service.NoSuchProfileException as e: return _error(404, str(e)) @@ -233,7 +215,6 @@ def get(self, profile): class _ResultFormatter: - def __init__(self, display): self._display = display self._headers = [d.title for d in display] @@ -248,7 +229,7 @@ def format_results(self, results, favorites): return { 'column_headers': self._headers, 'column_types': self._types, - 'results': [self._format_result(r) for r in results] + 'results': [self._format_result(r) for r in results], } def _format_result(self, result): @@ -259,10 +240,12 @@ def _format_result(self, result): result.fields.update(dict.fromkeys(self._personal_fields, result.is_personal)) return { - 'column_values': [result.fields.get(d.field, d.default) for d in self._display], + 'column_values': [ + result.fields.get(d.field, d.default) for d in self._display + ], 'relations': result.relations, 'source': result.source, - 'backend': result.backend + 'backend': result.backend, } def _is_favorite(self, result): @@ -280,7 +263,6 @@ def _is_favorite(self, result): class _FavoriteResultFormatter(_ResultFormatter): - def format_results(self, results): return super().format_results(results, []) diff --git a/wazo_dird/plugins/default_json/plugin.py b/wazo_dird/plugins/default_json/plugin.py index 1ca80239..ecd13420 100644 --- a/wazo_dird/plugins/default_json/plugin.py +++ b/wazo_dird/plugins/default_json/plugin.py @@ -5,13 +5,7 @@ from wazo_dird import BaseViewPlugin -from .http import ( - FavoritesRead, - FavoritesWrite, - Lookup, - Personal, - Reverse, -) +from .http import FavoritesRead, FavoritesWrite, Lookup, Personal, Reverse logger = logging.getLogger(__name__) @@ -51,10 +45,7 @@ def load(self, dependencies): api.add_resource( Reverse, self.reverse_url, - resource_class_args=( - reverse_service, - profile_service, - ), + resource_class_args=(reverse_service, profile_service), ) else: logger.error('%s disabled: no service plugin `reverse`', self.reverse_url) @@ -75,8 +66,12 @@ def load(self, dependencies): resource_class_args=(favorite_service,), ) else: - logger.error('%s disabled: no service plugin `favorites`', self.favorites_read_url) - logger.error('%s disabled: no service plugin `favorites`', self.favorites_write_url) + logger.error( + '%s disabled: no service plugin `favorites`', self.favorites_read_url + ) + logger.error( + '%s disabled: no service plugin `favorites`', self.favorites_write_url + ) if personal_service: api.add_resource( diff --git a/wazo_dird/plugins/default_json/tests/test_default_json_view.py b/wazo_dird/plugins/default_json/tests/test_default_json_view.py index 30545490..449d0206 100644 --- a/wazo_dird/plugins/default_json/tests/test_default_json_view.py +++ b/wazo_dird/plugins/default_json/tests/test_default_json_view.py @@ -11,47 +11,31 @@ from hamcrest import has_entry from hamcrest import has_item from hamcrest import not_ -from mock import ( - ANY, - call, - Mock, - sentinel as s, -) +from mock import ANY, call, Mock, sentinel as s from wazo_dird.helpers import DisplayColumn from wazo_dird import make_result_class from wazo_dird.plugins.tests.base_http_view_test_case import BaseHTTPViewTestCase -from ..plugin import ( - JsonViewPlugin, -) -from ..http import ( - FavoritesRead, - FavoritesWrite, - Lookup, - Personal, - _ResultFormatter, -) +from ..plugin import JsonViewPlugin +from ..http import FavoritesRead, FavoritesWrite, Lookup, Personal, _ResultFormatter UUID1 = str(uuid4()) UUID2 = str(uuid4()) class TestJsonViewPlugin(BaseHTTPViewTestCase): - def setUp(self): self.api = Mock() self.plugin = JsonViewPlugin() def test_that_load_with_no_lookup_service_does_not_add_route(self): - self.plugin.load({'config': {}, - 'http_namespace': Mock(), - 'api': self.api, - 'services': {}}) + self.plugin.load( + {'config': {}, 'http_namespace': Mock(), 'api': self.api, 'services': {}} + ) assert_that( - self.api.add_resource.call_args_list, - not_(has_item(call(Lookup, ANY))), + self.api.add_resource.call_args_list, not_(has_item(call(Lookup, ANY))) ) def test_that_load_adds_the_lookup_route(self): @@ -80,17 +64,18 @@ def test_that_load_adds_the_lookup_route(self): ) def test_that_load_with_no_favorites_service_does_not_add_route(self): - JsonViewPlugin().load({'config': {}, - 'http_namespace': Mock(), - 'api': self.api, - 'services': {}}) - - assert_that(self.api.add_resource.call_args_list, not_(has_item( - call(FavoritesRead, ANY), - ))) - assert_that(self.api.add_resource.call_args_list, not_(has_item( - call(FavoritesWrite, ANY), - ))) + JsonViewPlugin().load( + {'config': {}, 'http_namespace': Mock(), 'api': self.api, 'services': {}} + ) + + assert_that( + self.api.add_resource.call_args_list, + not_(has_item(call(FavoritesRead, ANY))), + ) + assert_that( + self.api.add_resource.call_args_list, + not_(has_item(call(FavoritesWrite, ANY))), + ) def test_that_load_adds_the_favorite_route(self): dependencies = { @@ -108,7 +93,11 @@ def test_that_load_adds_the_favorite_route(self): self.api.add_resource.assert_any_call( FavoritesRead, JsonViewPlugin.favorites_read_url, - resource_class_args=(s.favorite_service, s.display_service, s.profile_service), + resource_class_args=( + s.favorite_service, + s.display_service, + s.profile_service, + ), ) self.api.add_resource.assert_any_call( FavoritesWrite, @@ -117,12 +106,13 @@ def test_that_load_adds_the_favorite_route(self): ) def test_that_load_with_no_personal_service_does_not_add_route(self): - JsonViewPlugin().load({'config': {}, - 'http_namespace': Mock(), - 'api': self.api, - 'services': {}}) + JsonViewPlugin().load( + {'config': {}, 'http_namespace': Mock(), 'api': self.api, 'services': {}} + ) - assert_that(self.api.add_resource.call_args_list, not_(has_item(call(Personal, ANY)))) + assert_that( + self.api.add_resource.call_args_list, not_(has_item(call(Personal, ANY))) + ) def test_that_load_adds_the_personal_routes(self): dependencies = { @@ -152,12 +142,13 @@ def test_that_load_adds_the_personal_routes(self): class TestFormatResult(unittest.TestCase): - def setUp(self): self.source_name = 'my_source' self.xivo_id = 'my_xivo_abc' backend = 'my_backend' - self.SourceResult = make_result_class(backend, self.source_name, unique_column='id') + self.SourceResult = make_result_class( + backend, self.source_name, unique_column='id' + ) def test_that_format_results_adds_columns_headers(self): display = [ @@ -191,63 +182,105 @@ def test_that_format_results_adds_columns_types(self): assert_that(result, has_entries('column_types', expected_types)) def test_that_format_results_adds_results(self): - result1 = self.SourceResult({'id': 1, - 'firstname': 'Alice', - 'lastname': 'AAA', - 'telephoneNumber': '5555555555'}, - self.xivo_id, None, None, None, None) - result2 = self.SourceResult({'id': 'user_id', - 'firstname': 'Bob', - 'lastname': 'BBB', - 'telephoneNumber': '5555556666'}, - self.xivo_id, 'agent_id', 'user_id', UUID1, 'endpoint_id') + result1 = self.SourceResult( + { + 'id': 1, + 'firstname': 'Alice', + 'lastname': 'AAA', + 'telephoneNumber': '5555555555', + }, + self.xivo_id, + None, + None, + None, + None, + ) + result2 = self.SourceResult( + { + 'id': 'user_id', + 'firstname': 'Bob', + 'lastname': 'BBB', + 'telephoneNumber': '5555556666', + }, + self.xivo_id, + 'agent_id', + 'user_id', + UUID1, + 'endpoint_id', + ) display = [ DisplayColumn('Firstname', None, 'Unknown', 'firstname'), DisplayColumn('Lastname', None, '', 'lastname'), DisplayColumn(None, 'status', None, None), DisplayColumn('Number', 'office_number', None, 'telephoneNumber'), - DisplayColumn('Country', None, 'Canada', 'country') + DisplayColumn('Country', None, 'Canada', 'country'), ] formatter = _ResultFormatter(display) result = formatter.format_results([result1, result2], []) - assert_that(result, has_entries('results', [ + assert_that( + result, + has_entries( + 'results', + [ + { + 'column_values': ['Alice', 'AAA', None, '5555555555', 'Canada'], + 'relations': { + 'xivo_id': self.xivo_id, + 'agent_id': None, + 'user_id': None, + 'user_uuid': None, + 'endpoint_id': None, + 'source_entry_id': '1', + }, + 'source': self.source_name, + 'backend': 'my_backend', + }, + { + 'column_values': ['Bob', 'BBB', None, '5555556666', 'Canada'], + 'relations': { + 'xivo_id': self.xivo_id, + 'agent_id': 'agent_id', + 'user_id': 'user_id', + 'user_uuid': UUID1, + 'endpoint_id': 'endpoint_id', + 'source_entry_id': 'user_id', + }, + 'source': self.source_name, + 'backend': 'my_backend', + }, + ], + ), + ) + + def test_that_format_results_marks_favorites(self): + result1 = self.SourceResult( { - 'column_values': ['Alice', 'AAA', None, '5555555555', 'Canada'], - 'relations': {'xivo_id': self.xivo_id, - 'agent_id': None, - 'user_id': None, - 'user_uuid': None, - 'endpoint_id': None, - 'source_entry_id': '1'}, - 'source': self.source_name, - 'backend': 'my_backend', + 'id': 1, + 'firstname': 'Alice', + 'lastname': 'AAA', + 'telephoneNumber': '5555555555', }, + self.xivo_id, + None, + 1, + UUID1, + None, + ) + result2 = self.SourceResult( { - 'column_values': ['Bob', 'BBB', None, '5555556666', 'Canada'], - 'relations': {'xivo_id': self.xivo_id, - 'agent_id': 'agent_id', - 'user_id': 'user_id', - 'user_uuid': UUID1, - 'endpoint_id': 'endpoint_id', - 'source_entry_id': 'user_id'}, - 'source': self.source_name, - 'backend': 'my_backend', + 'id': 2, + 'firstname': 'Bob', + 'lastname': 'BBB', + 'telephoneNumber': '5555556666', }, - ])) - - def test_that_format_results_marks_favorites(self): - result1 = self.SourceResult({'id': 1, - 'firstname': 'Alice', - 'lastname': 'AAA', - 'telephoneNumber': '5555555555'}, - self.xivo_id, None, 1, UUID1, None) - result2 = self.SourceResult({'id': 2, - 'firstname': 'Bob', - 'lastname': 'BBB', - 'telephoneNumber': '5555556666'}, - self.xivo_id, 'agent_id', 2, UUID2, 'endpoint_id') + self.xivo_id, + 'agent_id', + 2, + UUID2, + 'endpoint_id', + ) display = [ DisplayColumn('Firstname', None, 'Unknown', 'firstname'), DisplayColumn('Lastname', None, '', 'lastname'), @@ -256,35 +289,70 @@ def test_that_format_results_marks_favorites(self): ] formatter = _ResultFormatter(display) - result = formatter.format_results([result1, result2], {'my_source': ['2'], - 'my_other_source': ['1', '2', '3']}) + result = formatter.format_results( + [result1, result2], {'my_source': ['2'], 'my_other_source': ['1', '2', '3']} + ) - assert_that(result, has_entry('results', contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', False)), - has_entry('column_values', contains('Bob', 'BBB', '5555556666', True))))) + assert_that( + result, + has_entry( + 'results', + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', False) + ), + has_entry( + 'column_values', contains('Bob', 'BBB', '5555556666', True) + ), + ), + ), + ) def test_that_format_results_marks_personal(self): - result1 = self.SourceResult({'id': 1, - 'firstname': 'Alice', - 'lastname': 'AAA', - 'telephoneNumber': '5555555555'}, - self.xivo_id, None, 1, UUID1, None) - result2 = self.SourceResult({'id': 2, - 'firstname': 'Bob', - 'lastname': 'BBB', - 'telephoneNumber': '5555556666'}, - self.xivo_id, 'agent_id', 2, UUID2, 'endpoint_id') + result1 = self.SourceResult( + { + 'id': 1, + 'firstname': 'Alice', + 'lastname': 'AAA', + 'telephoneNumber': '5555555555', + }, + self.xivo_id, + None, + 1, + UUID1, + None, + ) + result2 = self.SourceResult( + { + 'id': 2, + 'firstname': 'Bob', + 'lastname': 'BBB', + 'telephoneNumber': '5555556666', + }, + self.xivo_id, + 'agent_id', + 2, + UUID2, + 'endpoint_id', + ) result3 = make_result_class( 'personal', 'personal_source', unique_column='id', is_personal=True, - is_deletable=True)({ + is_deletable=True, + )( + { 'id': 'my-id', 'firstname': 'Charlie', 'lastname': 'CCC', - 'telephoneNumber': '5555557777' - }, self.xivo_id, None, None, None) + 'telephoneNumber': '5555557777', + }, + self.xivo_id, + None, + None, + None, + ) display = [ DisplayColumn('Firstname', None, 'Unknown', 'firstname'), @@ -296,7 +364,20 @@ def test_that_format_results_marks_personal(self): result = formatter.format_results([result1, result2, result3], {}) - assert_that(result, has_entry('results', contains_inanyorder( - has_entry('column_values', contains('Alice', 'AAA', '5555555555', False)), - has_entry('column_values', contains('Bob', 'BBB', '5555556666', False)), - has_entry('column_values', contains('Charlie', 'CCC', '5555557777', True))))) + assert_that( + result, + has_entry( + 'results', + contains_inanyorder( + has_entry( + 'column_values', contains('Alice', 'AAA', '5555555555', False) + ), + has_entry( + 'column_values', contains('Bob', 'BBB', '5555556666', False) + ), + has_entry( + 'column_values', contains('Charlie', 'CCC', '5555557777', True) + ), + ), + ), + ) diff --git a/wazo_dird/plugins/default_json/tests/test_http.py b/wazo_dird/plugins/default_json/tests/test_http.py index 37836cce..adaf4379 100644 --- a/wazo_dird/plugins/default_json/tests/test_http.py +++ b/wazo_dird/plugins/default_json/tests/test_http.py @@ -3,10 +3,7 @@ import unittest -from hamcrest import ( - assert_that, - equal_to, -) +from hamcrest import assert_that, equal_to from wazo_dird.helpers import DisplayColumn, DisplayAwareResource @@ -14,7 +11,6 @@ class TestMakeDisplays(unittest.TestCase): - def test_that_make_displays_with_no_config_returns_empty_dict(self): result = make_display({}) @@ -56,12 +52,7 @@ def test_that_make_displays_generate_display_dict(self): 'default': 'N/A', 'field': 'firstname', }, - { - 'title': 'ln', - 'type': None, - 'default': 'N/A', - 'field': 'LAST', - }, + {'title': 'ln', 'type': None, 'default': 'N/A', 'field': 'LAST'}, ], } diff --git a/wazo_dird/plugins/display_service/plugin.py b/wazo_dird/plugins/display_service/plugin.py index c8b73428..d463ae61 100644 --- a/wazo_dird/plugins/display_service/plugin.py +++ b/wazo_dird/plugins/display_service/plugin.py @@ -5,22 +5,17 @@ from wazo_dird.database.helpers import Session -from wazo_dird import ( - BaseServicePlugin, - database, -) +from wazo_dird import BaseServicePlugin, database logger = logging.getLogger(__name__) class DisplayServicePlugin(BaseServicePlugin): - def load(self, dependencies): return _DisplayService(database.DisplayCRUD(Session)) class _DisplayService: - def __init__(self, crud): self._display_crud = crud diff --git a/wazo_dird/plugins/displays/http.py b/wazo_dird/plugins/displays/http.py index 5ed74f82..fcda6c5f 100644 --- a/wazo_dird/plugins/displays/http.py +++ b/wazo_dird/plugins/displays/http.py @@ -9,23 +9,17 @@ from wazo_dird.auth import required_acl from wazo_dird.rest_api import AuthResource -from .schemas import ( - display_list_schema, - display_schema, - list_schema, -) +from .schemas import display_list_schema, display_schema, list_schema logger = logging.getLogger(__name__) class _BaseResource(AuthResource): - def __init__(self, display_service): self._display_service = display_service class Displays(_BaseResource): - @required_acl('dird.displays.read') def get(self): list_params, errors = list_schema.load(request.args) @@ -40,11 +34,7 @@ def get(self): filtered = self._display_service.count(visible_tenants, **list_params) total = self._display_service.count(visible_tenants) - return { - 'total': total, - 'filtered': filtered, - 'items': items, - } + return {'total': total, 'filtered': filtered, 'items': items} @required_acl('dird.displays.create') def post(self): @@ -55,7 +45,6 @@ def post(self): class Display(_BaseResource): - @required_acl('dird.displays.{display_uuid}.delete') def delete(self, display_uuid): tenant_uuid = Tenant.autodetect().uuid @@ -75,5 +64,7 @@ def put(self, display_uuid): tenant_uuid = Tenant.autodetect().uuid visible_tenants = self.get_visible_tenants(tenant_uuid) args = display_schema.load(request.get_json()).data - self._display_service.edit(display_uuid, visible_tenants=visible_tenants, **args) + self._display_service.edit( + display_uuid, visible_tenants=visible_tenants, **args + ) return '', 204 diff --git a/wazo_dird/plugins/displays/plugin.py b/wazo_dird/plugins/displays/plugin.py index 24682132..e3e406b5 100644 --- a/wazo_dird/plugins/displays/plugin.py +++ b/wazo_dird/plugins/displays/plugin.py @@ -7,15 +7,12 @@ class DisplaysViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] display_service = dependencies['services']['display'] api.add_resource( - http.Displays, - '/displays', - resource_class_args=(display_service,), + http.Displays, '/displays', resource_class_args=(display_service,) ) api.add_resource( diff --git a/wazo_dird/plugins/favorites_service/plugin.py b/wazo_dird/plugins/favorites_service/plugin.py index 9f8e9123..a5976f03 100644 --- a/wazo_dird/plugins/favorites_service/plugin.py +++ b/wazo_dird/plugins/favorites_service/plugin.py @@ -35,7 +35,6 @@ def __init__(self, source): class FavoritesServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -46,8 +45,10 @@ def load(self, args): bus = args['bus'] controller = args['controller'] except KeyError: - msg = ('%s should be loaded with "config", "source_manager" and "bus" but received: %s' - % (self.__class__.__name__, ','.join(args.keys()))) + msg = ( + '%s should be loaded with "config", "source_manager" and "bus" but received: %s' + % (self.__class__.__name__, ','.join(args.keys())) + ) raise ValueError(msg) crud = database.FavoriteCRUD(Session) @@ -90,7 +91,9 @@ def stop(self): def _async_list(self, source, contact_ids, args): raise_stopper = helpers.RaiseStopper(return_on_raise=[]) - future = self._executor.submit(raise_stopper.execute, source.list, contact_ids, args) + future = self._executor.submit( + raise_stopper.execute, source.list, contact_ids, args + ) future.name = source.name return future @@ -124,7 +127,9 @@ def favorites(self, profile_config, xivo_user_uuid, token=None): def favorite_ids(self, profile_config, xivo_user_uuid): favorites = self._crud.get(xivo_user_uuid) favorite_config = profile_config.get('services', {}).get('favorites', {}) - enabled_sources = {source['name']: source for source in favorite_config.get('sources', [])} + enabled_sources = { + source['name']: source for source in favorite_config.get('sources', []) + } by_uuid = defaultdict(list) by_name = defaultdict(list) @@ -151,11 +156,12 @@ def new_favorite(self, tenant_uuid, source_name, contact_id, xivo_user_uuid): backend = source['backend'] self._crud.create(xivo_user_uuid, backend, source_name, contact_id) - event = FavoriteAddedEvent(self._xivo_uuid, xivo_user_uuid, source_name, contact_id) + event = FavoriteAddedEvent( + self._xivo_uuid, xivo_user_uuid, source_name, contact_id + ) try: self._bus.publish( - event, - headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True}, + event, headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True} ) except OSError as e: logger.error('failed to publish bus event %s', e) @@ -173,5 +179,9 @@ def remove_favorite(self, tenant_uuid, source_name, contact_id, xivo_user_uuid): raise self.NoSuchSourceException(source_name) self._crud.delete(xivo_user_uuid, source_name, contact_id) - event = FavoriteDeletedEvent(self._xivo_uuid, xivo_user_uuid, source, contact_id) - self._bus.publish(event, headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True}) + event = FavoriteDeletedEvent( + self._xivo_uuid, xivo_user_uuid, source, contact_id + ) + self._bus.publish( + event, headers={'user_uuid:{uuid}'.format(uuid=xivo_user_uuid): True} + ) diff --git a/wazo_dird/plugins/favorites_service/tests/test_favorites_service.py b/wazo_dird/plugins/favorites_service/tests/test_favorites_service.py index f721cc52..a02de646 100644 --- a/wazo_dird/plugins/favorites_service/tests/test_favorites_service.py +++ b/wazo_dird/plugins/favorites_service/tests/test_favorites_service.py @@ -3,24 +3,13 @@ import unittest -from hamcrest import ( - assert_that, - equal_to, - not_, - none, -) -from mock import ( - ANY, - Mock, - patch, - sentinel as s, -) +from hamcrest import assert_that, equal_to, not_, none +from mock import ANY, Mock, patch, sentinel as s from ..plugin import FavoritesServicePlugin class TestFavoritesServicePlugin(unittest.TestCase): - def setUp(self): self._config = {} self._source_manager = Mock() @@ -28,7 +17,9 @@ def setUp(self): def test_load_no_config(self): plugin = FavoritesServicePlugin() - self.assertRaises(ValueError, plugin.load, {'source_manager': self._source_manager}) + self.assertRaises( + ValueError, plugin.load, {'source_manager': self._source_manager} + ) def test_load_no_sources(self): plugin = FavoritesServicePlugin() @@ -38,12 +29,14 @@ def test_load_no_sources(self): def test_that_load_returns_a_service(self): plugin = FavoritesServicePlugin() - service = plugin.load({ - 'source_manager': self._source_manager, - 'config': self._config, - 'bus': s.bus, - 'controller': s.controller, - }) + service = plugin.load( + { + 'source_manager': self._source_manager, + 'config': self._config, + 'bus': s.bus, + 'controller': s.controller, + } + ) assert_that(service, not_(none())) @@ -51,19 +44,17 @@ def test_that_load_returns_a_service(self): def test_that_load_injects_config_to_the_service(self, MockedFavoritesService): plugin = FavoritesServicePlugin() - service = plugin.load({ - 'config': self._config, - 'source_manager': self._source_manager, - 'bus': s.bus, - 'controller': s.controller, - }) + service = plugin.load( + { + 'config': self._config, + 'source_manager': self._source_manager, + 'bus': s.bus, + 'controller': s.controller, + } + ) MockedFavoritesService.assert_called_once_with( - self._config, - self._source_manager, - s.controller, - ANY, - s.bus, + self._config, self._source_manager, s.controller, ANY, s.bus ) assert_that(service, equal_to(MockedFavoritesService.return_value)) @@ -75,12 +66,14 @@ def test_no_error_on_unload_not_loaded(self): @patch('wazo_dird.plugins.favorites_service.plugin._FavoritesService') def test_that_unload_stops_the_services(self, MockedFavoritesService): plugin = FavoritesServicePlugin() - plugin.load({ - 'config': self._config, - 'source_manager': self._source_manager, - 'bus': s.bus, - 'controller': s.controller, - }) + plugin.load( + { + 'config': self._config, + 'source_manager': self._source_manager, + 'bus': s.bus, + 'controller': s.controller, + } + ) plugin.unload() diff --git a/wazo_dird/plugins/headers/http.py b/wazo_dird/plugins/headers/http.py index 04d037aa..6f9408b9 100644 --- a/wazo_dird/plugins/headers/http.py +++ b/wazo_dird/plugins/headers/http.py @@ -14,7 +14,6 @@ class Headers(LegacyAuthResource, DisplayAwareResource): - def __init__(self, display_service, profile_service): self.display_service = display_service self.profile_service = profile_service diff --git a/wazo_dird/plugins/headers/plugin.py b/wazo_dird/plugins/headers/plugin.py index ac462f01..c9db656d 100644 --- a/wazo_dird/plugins/headers/plugin.py +++ b/wazo_dird/plugins/headers/plugin.py @@ -11,7 +11,6 @@ class HeadersViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] display_service = dependencies['services'].get('display') diff --git a/wazo_dird/plugins/headers/tests/test_header_view.py b/wazo_dird/plugins/headers/tests/test_header_view.py index e969e282..876cb2a1 100644 --- a/wazo_dird/plugins/headers/tests/test_header_view.py +++ b/wazo_dird/plugins/headers/tests/test_header_view.py @@ -10,7 +10,6 @@ class TestFormatHeaders(unittest.TestCase): - def test_that_format_headers_adds_columns_headers(self): display = [ DisplayColumn('Firstname', None, 'Unknown', 'firstname'), diff --git a/wazo_dird/plugins/ldap_backend/http.py b/wazo_dird/plugins/ldap_backend/http.py index 5798efe1..15d2229f 100644 --- a/wazo_dird/plugins/ldap_backend/http.py +++ b/wazo_dird/plugins/ldap_backend/http.py @@ -3,16 +3,9 @@ from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) - -from .schemas import ( - list_schema, - source_schema, - source_list_schema, -) +from wazo_dird.helpers import SourceItem, SourceList + +from .schemas import list_schema, source_schema, source_list_schema class LDAPList(SourceList): diff --git a/wazo_dird/plugins/ldap_backend/plugin.py b/wazo_dird/plugins/ldap_backend/plugin.py index 9af62597..28a5aac7 100644 --- a/wazo_dird/plugins/ldap_backend/plugin.py +++ b/wazo_dird/plugins/ldap_backend/plugin.py @@ -26,7 +26,6 @@ class LDAPView(BaseBackendView): class LDAPPlugin(BaseSourcePlugin): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ldap_factory = _LDAPFactory() @@ -35,7 +34,7 @@ def __init__(self, *args, **kwargs): def load(self, args): self._ldap_config = self.ldap_factory.new_ldap_config(args['config']) self._ldap_result_formatter = self.ldap_factory.new_ldap_result_formatter( - self._ldap_config, + self._ldap_config ) self._ldap_client = self.ldap_factory.new_ldap_client(self._ldap_config) self._ldap_client.set_up() @@ -84,7 +83,6 @@ def _first_match_and_format(self, filter_str): class _LDAPFactory: - def new_ldap_config(self, config): return _LDAPConfig(config) @@ -103,12 +101,13 @@ class _LDAPConfig: DEFAULT_LDAP_TIMEOUT = 1.0 def __init__(self, config): - if ( - not config.get('ldap_custom_filter') - and not config.get(BaseSourcePlugin.SEARCHED_COLUMNS) + if not config.get('ldap_custom_filter') and not config.get( + BaseSourcePlugin.SEARCHED_COLUMNS ): - raise LookupError("%s need a searched_columns OR" - "ldap_custom_filter in it's configuration" % config.get('name')) + raise LookupError( + "%s need a searched_columns OR" + "ldap_custom_filter in it's configuration" % config.get('name') + ) self._config = config @@ -143,7 +142,9 @@ def ldap_password(self): return self._config.get('ldap_password', self.DEFAULT_LDAP_PASSWORD) def ldap_network_timeout(self): - return self._config.get('ldap_network_timeout', self.DEFAULT_LDAP_NETWORK_TIMEOUT) + return self._config.get( + 'ldap_network_timeout', self.DEFAULT_LDAP_NETWORK_TIMEOUT + ) def ldap_timeout(self): return self._config.get('ldap_timeout', self.DEFAULT_LDAP_TIMEOUT) @@ -170,9 +171,11 @@ def build_search_filter(self, term): if ldap_custom_filter and searched_columns: custom_filter = self._build_search_filter_from_custom_filter(term_escaped) - generated_filter = self._build_search_filter_from_searched_columns(term_escaped) + generated_filter = self._build_search_filter_from_searched_columns( + term_escaped + ) return self._build_filter_from_custom_and_generated_filter( - custom_filter, generated_filter, + custom_filter, generated_filter ) elif ldap_custom_filter: return self._build_search_filter_from_custom_filter(term_escaped) @@ -188,29 +191,39 @@ def build_first_match_filter(self, term): if ldap_custom_filter and first_matched_columns: custom_filter = self._build_search_filter_from_custom_filter(term_escaped) generated_filter = self._build_exact_search_filter_from_first_matched_columns( - term_escaped, + term_escaped ) return self._build_filter_from_custom_and_generated_filter( - custom_filter, generated_filter, + custom_filter, generated_filter ) elif ldap_custom_filter: return self._build_search_filter_from_custom_filter(term_escaped) elif first_matched_columns: - return self._build_exact_search_filter_from_first_matched_columns(term_escaped) + return self._build_exact_search_filter_from_first_matched_columns( + term_escaped + ) return None - def _build_filter_from_custom_and_generated_filter(self, custom_filter, generated_filter): - return '(&{custom}{generated})'.format(custom=custom_filter, generated=generated_filter) + def _build_filter_from_custom_and_generated_filter( + self, custom_filter, generated_filter + ): + return '(&{custom}{generated})'.format( + custom=custom_filter, generated=generated_filter + ) def _build_search_filter_from_custom_filter(self, term_escaped): return self._config['ldap_custom_filter'].replace('%Q', term_escaped) def _build_search_filter_from_searched_columns(self, term_escaped): - list_ = list('(%s=*%s*)' % (attr, term_escaped) for attr in self.searched_columns()) + list_ = list( + '(%s=*%s*)' % (attr, term_escaped) for attr in self.searched_columns() + ) return self._build_filter_from_list(list_) def _build_exact_search_filter_from_first_matched_columns(self, term_escaped): - list_ = list('(%s=%s)' % (attr, term_escaped) for attr in self.first_matched_columns()) + list_ = list( + '(%s=%s)' % (attr, term_escaped) for attr in self.first_matched_columns() + ) return self._build_filter_from_list(list_) def _build_filter_from_list(self, l): @@ -243,7 +256,6 @@ def _convert_binary_uid(self, uid): class _LDAPClient: - def __init__(self, ldap_config, ldap_obj_factory=ldap.initialize): self._ldap_config = ldap_config self._ldap_obj_factory = ldap_obj_factory @@ -273,15 +285,16 @@ def _set_up(self): def _new_ldap_obj(self): ldap_obj = self._ldap_obj_factory(self._ldap_config.ldap_uri()) ldap_obj.set_option(ldap.OPT_REFERRALS, 0) - ldap_obj.set_option(ldap.OPT_NETWORK_TIMEOUT, self._ldap_config.ldap_network_timeout()) + ldap_obj.set_option( + ldap.OPT_NETWORK_TIMEOUT, self._ldap_config.ldap_network_timeout() + ) ldap_obj.set_option(ldap.OPT_TIMEOUT, self._ldap_config.ldap_timeout()) return ldap_obj def _bind(self): try: self._ldap_obj.simple_bind_s( - self._ldap_config.ldap_username(), - self._ldap_config.ldap_password(), + self._ldap_config.ldap_username(), self._ldap_config.ldap_password() ) except ldap.LDAPError as e: logger.error('LDAP "%s": bind error: %r', self._name, e) @@ -313,17 +326,22 @@ def _search(self, filter_str, limit): results = [] try: - results = self._ldap_obj.search_ext_s(self._base_dn, - ldap.SCOPE_SUBTREE, - filter_str, - self._attributes, - sizelimit=limit) + results = self._ldap_obj.search_ext_s( + self._base_dn, + ldap.SCOPE_SUBTREE, + filter_str, + self._attributes, + sizelimit=limit, + ) except ldap.FILTER_ERROR: - logger.warning('LDAP "%s": search error: invalid filter "%s"', self._name, filter_str) + logger.warning( + 'LDAP "%s": search error: invalid filter "%s"', self._name, filter_str + ) except ldap.NO_SUCH_OBJECT: logger.warning( 'LDAP "%s": search error: no such object "%s"', - self._name, self._ldap_config.ldap_base_dn(), + self._name, + self._ldap_config.ldap_base_dn(), ) except ldap.TIMEOUT: logger.warning('LDAP "%s": search error: timed out', self._name) @@ -335,7 +353,6 @@ def _search(self, filter_str, limit): class _LDAPResultFormatter: - def __init__(self, ldap_config): self._unique_column = ldap_config.unique_column() self._bin_uuid = ldap_config.has_binary_uuid() @@ -343,7 +360,7 @@ def __init__(self, ldap_config): 'ldap', ldap_config.name(), self._unique_column, - ldap_config.format_columns() + ldap_config.format_columns(), ) def format(self, raw_results): diff --git a/wazo_dird/plugins/ldap_backend/schemas.py b/wazo_dird/plugins/ldap_backend/schemas.py index 4636418c..e16a072e 100644 --- a/wazo_dird/plugins/ldap_backend/schemas.py +++ b/wazo_dird/plugins/ldap_backend/schemas.py @@ -2,11 +2,7 @@ # SPDX-License-Identifier: GPL-3.0-or-later from xivo.mallow import fields -from xivo.mallow.validate import ( - Length, - Range, - OneOf, -) +from xivo.mallow.validate import Length, Range, OneOf from xivo.mallow_helpers import ListSchema as _ListSchema from wazo_dird.schemas import BaseSourceSchema @@ -21,7 +17,7 @@ class SourceSchema(BaseSourceSchema): ldap_timeout = fields.Float(validate=Range(min=0), default=1.0) unique_column = fields.String(Length(min=1, max=128), allownone=True, missing=None) unique_column_format = fields.String( - validate=OneOf(['string', 'binary_uuid']), missing='string', + validate=OneOf(['string', 'binary_uuid']), missing='string' ) diff --git a/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py b/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py index 61b3e00b..d5f64604 100644 --- a/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py +++ b/wazo_dird/plugins/ldap_backend/tests/test_ldap_plugin.py @@ -23,7 +23,6 @@ class TestLDAPPlugin(unittest.TestCase): - def setUp(self): self.config = {'config': sentinel} self.ldap_config = Mock(_LDAPConfig) @@ -31,7 +30,9 @@ def setUp(self): self.ldap_client = Mock(_LDAPClient) self.ldap_factory = Mock(_LDAPFactory) self.ldap_factory.new_ldap_config.return_value = self.ldap_config - self.ldap_factory.new_ldap_result_formatter.return_value = self.ldap_result_formatter + self.ldap_factory.new_ldap_result_formatter.return_value = ( + self.ldap_result_formatter + ) self.ldap_factory.new_ldap_client.return_value = self.ldap_client self.ldap_plugin = LDAPPlugin() self.ldap_plugin.ldap_factory = self.ldap_factory @@ -40,7 +41,9 @@ def test_load(self): self.ldap_plugin.load(self.config) self.ldap_factory.new_ldap_config.assert_called_once_with(self.config['config']) - self.ldap_factory.new_ldap_result_formatter.assert_called_once_with(self.ldap_config) + self.ldap_factory.new_ldap_result_formatter.assert_called_once_with( + self.ldap_config + ) self.ldap_factory.new_ldap_client.assert_called_once_with(self.ldap_config) self.ldap_client.set_up.assert_called_once_with() @@ -61,7 +64,9 @@ def test_search(self): self.ldap_config.build_search_filter.assert_called_once_with(term) self.ldap_client.search.assert_called_once_with(sentinel.filter) - self.ldap_result_formatter.format.assert_called_once_with(sentinel.search_result) + self.ldap_result_formatter.format.assert_called_once_with( + sentinel.search_result + ) self.assertIs(result, sentinel.format_result) def test_first_match(self): @@ -71,7 +76,9 @@ def test_first_match(self): (sentinel.result_1_dn, sentinel.result_1_attrs), sentinel.result_2, ] - self.ldap_result_formatter.format_one_result.return_value = sentinel.format_result + self.ldap_result_formatter.format_one_result.return_value = ( + sentinel.format_result + ) self.ldap_plugin.load(self.config) result = self.ldap_plugin.first_match(exten) @@ -79,7 +86,7 @@ def test_first_match(self): self.ldap_config.build_first_match_filter.assert_called_once_with(exten) self.ldap_client.search.assert_called_once_with(sentinel.filter, 1) self.ldap_result_formatter.format_one_result.assert_called_once_with( - sentinel.result_1_attrs, + sentinel.result_1_attrs ) self.assertIs(result, sentinel.format_result) @@ -117,7 +124,9 @@ def test_list_with_uids(self): self.ldap_config.build_list_filter.assert_called_once_with(uids) self.ldap_client.search.assert_called_once_with(sentinel.filter) - self.ldap_result_formatter.format.assert_called_once_with(sentinel.search_result) + self.ldap_result_formatter.format.assert_called_once_with( + sentinel.search_result + ) self.assertIs(result, sentinel.format_result) def test_list_no_unique_column(self): @@ -132,7 +141,6 @@ def test_list_no_unique_column(self): class TestLDAPFactory(unittest.TestCase): - def setUp(self): self.ldap_factory = _LDAPFactory() @@ -156,7 +164,6 @@ def test_ldap_result_formatter(self): class TestLDAPConfig(unittest.TestCase): - def new_ldap_config(self, config): config.update({BaseSourcePlugin.SEARCHED_COLUMNS: ['cn']}) return _LDAPConfig(config) @@ -189,9 +196,7 @@ def test_unique_column_format_binary_uuid(self): def test_unique_column(self): value = 'entryUUID' - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: value, - }) + ldap_config = self.new_ldap_config({BaseSourcePlugin.UNIQUE_COLUMN: value}) self.assertEqual(value, ldap_config.unique_column()) @@ -203,9 +208,7 @@ def test_unique_column_when_absent(self): def test_format_columns(self): value = {'firstname': '{givenName}'} - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.FORMAT_COLUMNS: value, - }) + ldap_config = self.new_ldap_config({BaseSourcePlugin.FORMAT_COLUMNS: value}) self.assertEqual(value, ldap_config.format_columns()) @@ -273,7 +276,7 @@ def test_ldap_network_timeout_when_absent(self): ldap_config = self.new_ldap_config({}) self.assertEqual( - _LDAPConfig.DEFAULT_LDAP_NETWORK_TIMEOUT, ldap_config.ldap_network_timeout(), + _LDAPConfig.DEFAULT_LDAP_NETWORK_TIMEOUT, ldap_config.ldap_network_timeout() ) def test_ldap_timeout(self): @@ -294,101 +297,112 @@ def test_attributes_with_nothing(self): self.assertEqual(None, ldap_config.attributes()) def test_attributes_with_unique_column_only_returns_none(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID', - }) + ldap_config = self.new_ldap_config( + {BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID'} + ) self.assertEqual(None, ldap_config.attributes()) def test_attributes_with_format_columns(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.FORMAT_COLUMNS: { - 'firstname': '{givenName}', - 'lastname': '{sn}', - }, - }) + ldap_config = self.new_ldap_config( + { + BaseSourcePlugin.FORMAT_COLUMNS: { + 'firstname': '{givenName}', + 'lastname': '{sn}', + } + } + ) assert_that(ldap_config.attributes(), contains_inanyorder('givenName', 'sn')) def test_attributes_with_unique_column_and_format_columns(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.FORMAT_COLUMNS: { - 'firstname': '{givenName}', - 'lastname': '{sn}', - }, - BaseSourcePlugin.UNIQUE_COLUMN: 'uid' - }) + ldap_config = self.new_ldap_config( + { + BaseSourcePlugin.FORMAT_COLUMNS: { + 'firstname': '{givenName}', + 'lastname': '{sn}', + }, + BaseSourcePlugin.UNIQUE_COLUMN: 'uid', + } + ) - assert_that(ldap_config.attributes(), contains_inanyorder('givenName', 'sn', 'uid')) + assert_that( + ldap_config.attributes(), contains_inanyorder('givenName', 'sn', 'uid') + ) def test_attributes_with_unique_column_in_format_columns(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.FORMAT_COLUMNS: { - 'firstname': '{givenName}', - 'lastname': '{sn}', - }, - BaseSourcePlugin.UNIQUE_COLUMN: 'sn' - }) + ldap_config = self.new_ldap_config( + { + BaseSourcePlugin.FORMAT_COLUMNS: { + 'firstname': '{givenName}', + 'lastname': '{sn}', + }, + BaseSourcePlugin.UNIQUE_COLUMN: 'sn', + } + ) assert_that(ldap_config.attributes(), contains_inanyorder('givenName', 'sn')) def test_build_search_filter_with_searched_columns_and_without_custom_filter(self): - ldap_config = _LDAPConfig({ - BaseSourcePlugin.SEARCHED_COLUMNS: ['cn'], - }) + ldap_config = _LDAPConfig({BaseSourcePlugin.SEARCHED_COLUMNS: ['cn']}) self.assertEqual('(cn=*foo*)', ldap_config.build_search_filter('foo')) def test_build_search_filter_without_searched_columns_and_with_custom_filter(self): - ldap_config = _LDAPConfig({ - 'ldap_custom_filter': '(cn=*%Q*)', - }) + ldap_config = _LDAPConfig({'ldap_custom_filter': '(cn=*%Q*)'}) self.assertEqual('(cn=*foo*)', ldap_config.build_search_filter('foo')) def test_build_search_filter_with_searched_columns_and_custom_filter(self): - ldap_config = _LDAPConfig({ - BaseSourcePlugin.SEARCHED_COLUMNS: ['sn'], - 'ldap_custom_filter': '(cn=*%Q*)', - }) + ldap_config = _LDAPConfig( + { + BaseSourcePlugin.SEARCHED_COLUMNS: ['sn'], + 'ldap_custom_filter': '(cn=*%Q*)', + } + ) - self.assertEqual('(&(cn=*foo*)(sn=*foo*))', ldap_config.build_search_filter('foo')) + self.assertEqual( + '(&(cn=*foo*)(sn=*foo*))', ldap_config.build_search_filter('foo') + ) - def test_build_search_filter_with_searched_columns_and_custom_filter_unicode_term(self): - ldap_config = _LDAPConfig({ - BaseSourcePlugin.SEARCHED_COLUMNS: ['sn'], - 'ldap_custom_filter': str('(cn=*%Q*)'), - }) + def test_build_search_filter_with_searched_columns_and_custom_filter_unicode_term( + self + ): + ldap_config = _LDAPConfig( + { + BaseSourcePlugin.SEARCHED_COLUMNS: ['sn'], + 'ldap_custom_filter': str('(cn=*%Q*)'), + } + ) self.assertEqual( - '(&(cn=*Québec*)(sn=*Québec*))', - ldap_config.build_search_filter('Québec') + '(&(cn=*Québec*)(sn=*Québec*))', ldap_config.build_search_filter('Québec') ) def test_build_search_filter_searched_columns_escape_term(self): - ldap_config = _LDAPConfig({ - BaseSourcePlugin.SEARCHED_COLUMNS: ['cn'], - }) + ldap_config = _LDAPConfig({BaseSourcePlugin.SEARCHED_COLUMNS: ['cn']}) term = 'f)f' escaped_term = 'f\\29f' - self.assertEqual('(cn=*%s*)' % escaped_term, ldap_config.build_search_filter(term)) + self.assertEqual( + '(cn=*%s*)' % escaped_term, ldap_config.build_search_filter(term) + ) def test_build_search_filter_custom_filter_escape_term(self): - ldap_config = _LDAPConfig({ - 'ldap_custom_filter': '(cn=*%Q*)', - }) + ldap_config = _LDAPConfig({'ldap_custom_filter': '(cn=*%Q*)'}) term = 'f)f' escaped_term = 'f\\29f' - self.assertEqual('(cn=*%s*)' % escaped_term, ldap_config.build_search_filter(term)) + self.assertEqual( + '(cn=*%s*)' % escaped_term, ldap_config.build_search_filter(term) + ) def test_build_search_filter_multiple_columns(self): - ldap_config = _LDAPConfig({ - BaseSourcePlugin.SEARCHED_COLUMNS: ['givenName', 'sn'], - }) + ldap_config = _LDAPConfig( + {BaseSourcePlugin.SEARCHED_COLUMNS: ['givenName', 'sn']} + ) term = 'foo' expected = '(|(givenName=*{term}*)(sn=*{term}*))'.format(term=term) @@ -396,17 +410,17 @@ def test_build_search_filter_multiple_columns(self): self.assertEqual(expected, ldap_config.build_search_filter(term)) def test_build_list_filter_no_item(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID', - }) + ldap_config = self.new_ldap_config( + {BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID'} + ) uids = [] self.assertFalse(ldap_config.build_list_filter(uids)) def test_build_list_filter_one_item(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID', - }) + ldap_config = self.new_ldap_config( + {BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID'} + ) uids = ['foo'] self.assertEqual('(entryUUID=foo)', ldap_config.build_list_filter(uids)) @@ -414,25 +428,30 @@ def test_build_list_filter_one_item(self): def test_build_list_filter_binary(self): uuid = 'f3bc2a27-7f38-4e30-adf5-873fe5ac484f' binary_uuid = '\\f3\\bc\\2a\\27\\7f\\38\\4e\\30\\ad\\f5\\87\\3f\\e5\\ac\\48\\4f' - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: 'objectGUID', - 'unique_column_format': 'binary_uuid', - }) + ldap_config = self.new_ldap_config( + { + BaseSourcePlugin.UNIQUE_COLUMN: 'objectGUID', + 'unique_column_format': 'binary_uuid', + } + ) uids = [uuid] - self.assertEqual('(objectGUID=%s)' % binary_uuid, ldap_config.build_list_filter(uids)) + self.assertEqual( + '(objectGUID=%s)' % binary_uuid, ldap_config.build_list_filter(uids) + ) def test_build_list_filter_two_items(self): - ldap_config = self.new_ldap_config({ - BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID', - }) + ldap_config = self.new_ldap_config( + {BaseSourcePlugin.UNIQUE_COLUMN: 'entryUUID'} + ) uids = ['foo', 'bar'] - self.assertEqual('(|(entryUUID=foo)(entryUUID=bar))', ldap_config.build_list_filter(uids)) + self.assertEqual( + '(|(entryUUID=foo)(entryUUID=bar))', ldap_config.build_list_filter(uids) + ) class TestLDAPClient(unittest.TestCase): - def setUp(self): self.uri = 'ldap://example.org' self.base_dn = 'ou=people,dc=foobar' @@ -454,7 +473,9 @@ def test_set_up(self): self.ldap_client.set_up() self.ldap_obj_factory.assert_called_once_with(self.uri) - self.ldap_obj.simple_bind_s.assert_called_once_with(self.username, self.password) + self.ldap_obj.simple_bind_s.assert_called_once_with( + self.username, self.password + ) def test_set_up_when_already_set_up(self): self.ldap_client.set_up() @@ -483,11 +504,7 @@ def test_search(self): result = self.ldap_client.search('foo') self.ldap_obj.search_ext_s.assert_called_once_with( - self.base_dn, - ANY, - 'foo', - self.attributes, - sizelimit=-1, + self.base_dn, ANY, 'foo', self.attributes, sizelimit=-1 ) self.assertEqual(1, self.ldap_obj_factory.call_count) self.assertIs(result, sentinel) @@ -522,7 +539,6 @@ def test_multiple_search(self): class TestLDAPResultFormatter(unittest.TestCase): - def setUp(self): self.name = 'foo' self.unique_column = 'entryUUID' @@ -532,14 +548,14 @@ def setUp(self): self.ldap_config.unique_column.return_value = self.unique_column self.ldap_config.format_columns.return_value = self.format_columns self.SourceResult = make_result_class( - 'ldap', self.name, self.unique_column, self.format_columns, + 'ldap', self.name, self.unique_column, self.format_columns ) def test_format(self): formatter = self._new_formatter(has_binary_uuid=False) raw_results = [ - ('dn', {'entryUUID': [b'0123'], 'givenName': [b'Gr\xc3\xa9goire']}), + ('dn', {'entryUUID': [b'0123'], 'givenName': [b'Gr\xc3\xa9goire']}) ] expected_results = [ self.SourceResult({'entryUUID': '0123', 'givenName': 'Grégoire'}) @@ -555,9 +571,7 @@ def test_format_with_binary_uid(self): binary_uuid = os.urandom(16) encoded_uid = str(uuid.UUID(bytes=binary_uuid)) - raw_results = [ - ('dn', {'entryUUID': [binary_uuid], 'givenName': [b'John']}), - ] + raw_results = [('dn', {'entryUUID': [binary_uuid], 'givenName': [b'John']})] expected_results = [ self.SourceResult({'entryUUID': encoded_uid, 'givenName': 'John'}) ] @@ -571,7 +585,10 @@ def test_format_with_referals(self): raw_results = [ ('dn', {'entryUUID': [b'0123'], 'givenName': [b'John']}), - (None, ['ldap://b.example.com/cn=test,dc=lan-quebec,dc=avencall,dc=com??sub']), + ( + None, + ['ldap://b.example.com/cn=test,dc=lan-quebec,dc=avencall,dc=com??sub'], + ), ] expected_results = [ self.SourceResult({'entryUUID': '0123', 'givenName': 'John'}) @@ -585,7 +602,9 @@ def test_format_one_result(self): formatter = self._new_formatter(has_binary_uuid=False) raw_result = ('dn', {'entryUUID': [b'0123'], 'givenName': [b'Gr\xc3\xa9goire']}) - expected_result = self.SourceResult({'entryUUID': '0123', 'givenName': 'Grégoire'}) + expected_result = self.SourceResult( + {'entryUUID': '0123', 'givenName': 'Grégoire'} + ) dn, attrs = raw_result result = formatter.format_one_result(attrs) diff --git a/wazo_dird/plugins/lookup_service/plugin.py b/wazo_dird/plugins/lookup_service/plugin.py index 00890b75..bd80e9a7 100644 --- a/wazo_dird/plugins/lookup_service/plugin.py +++ b/wazo_dird/plugins/lookup_service/plugin.py @@ -13,7 +13,6 @@ class LookupServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -26,8 +25,10 @@ def load(self, dependencies): ) return self._service except KeyError: - msg = ('%s should be loaded with "config" and "source_manager" but received: %s' - % (self.__class__.__name__, ','.join(dependencies.keys()))) + msg = ( + '%s should be loaded with "config" and "source_manager" but received: %s' + % (self.__class__.__name__, ','.join(dependencies.keys())) + ) raise ValueError(msg) def unload(self): @@ -53,7 +54,9 @@ def _async_search(self, source, term, args): future.name = source.name return future - def lookup(self, profile_config, tenant_uuid, term, xivo_user_uuid, args=None, token=None): + def lookup( + self, profile_config, tenant_uuid, term, xivo_user_uuid, args=None, token=None + ): args = args or {} futures = [] sources = self.source_from_profile(profile_config) diff --git a/wazo_dird/plugins/lookup_service/tests/test_lookup.py b/wazo_dird/plugins/lookup_service/tests/test_lookup.py index 31df45c5..e7192252 100644 --- a/wazo_dird/plugins/lookup_service/tests/test_lookup.py +++ b/wazo_dird/plugins/lookup_service/tests/test_lookup.py @@ -15,14 +15,15 @@ class TestLookupServicePlugin(unittest.TestCase): - def setUp(self): self._source_manager = Mock() def test_load_no_config(self): plugin = LookupServicePlugin() - self.assertRaises(ValueError, plugin.load, {'source_manager': self._source_manager}) + self.assertRaises( + ValueError, plugin.load, {'source_manager': self._source_manager} + ) def test_load_no_sources(self): plugin = LookupServicePlugin() diff --git a/wazo_dird/plugins/office365_backend/exceptions.py b/wazo_dird/plugins/office365_backend/exceptions.py index d433a317..80232c0d 100644 --- a/wazo_dird/plugins/office365_backend/exceptions.py +++ b/wazo_dird/plugins/office365_backend/exceptions.py @@ -20,7 +20,5 @@ class MicrosoftTokenNotFoundException(APIException): def __init__(self, user_uuid): message = 'No microsoft token found.' - details = { - 'user_uuid': user_uuid, - } + details = {'user_uuid': user_uuid} super().__init__(self.code, message, 'no-token-found', details) diff --git a/wazo_dird/plugins/office365_backend/http.py b/wazo_dird/plugins/office365_backend/http.py index 3e126aca..30539955 100644 --- a/wazo_dird/plugins/office365_backend/http.py +++ b/wazo_dird/plugins/office365_backend/http.py @@ -32,15 +32,16 @@ def get(self, source_uuid): tenant = Tenant.autodetect() source = self.source_service.get(self.BACKEND, source_uuid, [tenant.uuid]) - microsoft_token = get_microsoft_access_token(user_uuid, token_from_request, **source['auth']) + microsoft_token = get_microsoft_access_token( + user_uuid, token_from_request, **source['auth'] + ) contacts = self.office365.get_contacts(microsoft_token, source['endpoint']) - return { - 'filtered': len(contacts), - 'items': contacts, - 'total': len(contacts), - }, 200 + return ( + {'filtered': len(contacts), 'items': contacts, 'total': len(contacts)}, + 200, + ) class MicrosoftList(SourceList): diff --git a/wazo_dird/plugins/office365_backend/plugin.py b/wazo_dird/plugins/office365_backend/plugin.py index f050759f..faa0ac46 100644 --- a/wazo_dird/plugins/office365_backend/plugin.py +++ b/wazo_dird/plugins/office365_backend/plugin.py @@ -37,7 +37,6 @@ def load(self, dependencies): class Office365Plugin(BaseSourcePlugin): - def load(self, dependencies): config = dependencies['config'] self.auth = config['auth'] @@ -50,15 +49,12 @@ def load(self, dependencies): if 'reverse' not in format_columns: logger.info( 'no "reverse" column has been configured on %s will use "givenName"', - self.name + self.name, ) format_columns['reverse'] = '{givenName}' self._SourceResult = make_result_class( - 'office365', - self.name, - self.unique_column, - format_columns, + 'office365', self.name, self.unique_column, format_columns ) self._searched_columns = config.get(self.SEARCHED_COLUMNS, []) @@ -82,7 +78,9 @@ def search(self, term, args=None): except MicrosoftTokenNotFoundException: return [] - contacts = self.office365.get_contacts_with_term(microsoft_token, term, self.endpoint) + contacts = self.office365.get_contacts_with_term( + microsoft_token, term, self.endpoint + ) updated_contacts = self._update_contact_fields(contacts) lowered_term = term.lower() @@ -107,7 +105,9 @@ def list(self, unique_ids, args=None): contacts = self.office365.get_contacts(microsoft_token, self.endpoint) updated_contacts = self._update_contact_fields(contacts) - filtered_contacts = [c for c in updated_contacts if c[self.unique_column] in unique_ids] + filtered_contacts = [ + c for c in updated_contacts if c[self.unique_column] in unique_ids + ] return [self._SourceResult(contact) for contact in filtered_contacts] @@ -122,7 +122,9 @@ def first_match(self, term, args=None): try: microsoft_token = self._get_microsoft_token(**args) except MicrosoftTokenNotFoundException: - logger.debug('could not find a matching microsoft token, aborting first_match') + logger.debug( + 'could not find a matching microsoft token, aborting first_match' + ) return None contacts = self.office365.get_contacts(microsoft_token, self.endpoint) diff --git a/wazo_dird/plugins/office365_backend/schemas.py b/wazo_dird/plugins/office365_backend/schemas.py index 70d9b25e..9ba3e7da 100644 --- a/wazo_dird/plugins/office365_backend/schemas.py +++ b/wazo_dird/plugins/office365_backend/schemas.py @@ -13,7 +13,7 @@ class SourceSchema(BaseSourceSchema): auth = fields.Dict( keys=fields.String(validate=Length(min=1, max=64)), - values=fields.String(validate=Length(min=1, max=64)) + values=fields.String(validate=Length(min=1, max=64)), ) endpoint = fields.String( missing='https://graph.microsoft.com/v1.0/me/contacts', diff --git a/wazo_dird/plugins/office365_backend/services.py b/wazo_dird/plugins/office365_backend/services.py index 9c3d84d9..c07a4de4 100644 --- a/wazo_dird/plugins/office365_backend/services.py +++ b/wazo_dird/plugins/office365_backend/services.py @@ -20,9 +20,7 @@ class Office365Service: def get_contacts_with_term(self, microsoft_token, term, url): headers = self.headers(microsoft_token) - query_params = { - "search": term - } + query_params = {"search": term} try: response = requests.get(url, headers=headers, params=query_params) if response.status_code == 200: @@ -31,7 +29,9 @@ def get_contacts_with_term(self, microsoft_token, term, url): else: return [] except requests.RequestException as e: - logger.error('Unable to get contacts from this endpoint: %s, error : %s', url, e) + logger.error( + 'Unable to get contacts from this endpoint: %s, error : %s', url, e + ) return [] def get_contacts(self, microsoft_token, url): @@ -42,8 +42,12 @@ def get_contacts(self, microsoft_token, url): logger.debug('Successfully fetched contacts from microsoft.') return response.json().get('value', []) else: - logger.error('An error occured while fetching information from microsoft endpoint') - raise UnexpectedEndpointException(endpoint=url, error_code=response.status_code) + logger.error( + 'An error occured while fetching information from microsoft endpoint' + ) + raise UnexpectedEndpointException( + endpoint=url, error_code=response.status_code + ) except requests.RequestException: raise UnexpectedEndpointException(endpoint=url) @@ -53,7 +57,7 @@ def headers(self, microsoft_token): 'Authorization': 'Bearer {0}'.format(microsoft_token), 'Accept': 'application/json', 'client-request-id': str(uuid.uuid4), - 'return-client-request-id': 'true' + 'return-client-request-id': 'true', } @@ -65,11 +69,17 @@ def get_microsoft_access_token(user_uuid, wazo_token, **auth_config): logger.error('Microsoft token could not be fetched from wazo-auth, error %s', e) raise MicrosoftTokenNotFoundException(user_uuid) except requests.exceptions.ConnectionError as e: - logger.error('Unable to connect auth-client for the given parameters: %s, error :%s.', auth_config, e) + logger.error( + 'Unable to connect auth-client for the given parameters: %s, error :%s.', + auth_config, + e, + ) raise MicrosoftTokenNotFoundException(user_uuid) except requests.RequestException as e: logger.error('Error occured while connecting to wazo-auth, error :%s', e) def get_first_email(contact_information): - return next(iter(contact_information.get('emailAddresses') or []), {}).get('address') + return next(iter(contact_information.get('emailAddresses') or []), {}).get( + 'address' + ) diff --git a/wazo_dird/plugins/office365_backend/tests/test_office365_plugin.py b/wazo_dird/plugins/office365_backend/tests/test_office365_plugin.py index 2c3cc0cc..97d4a44f 100644 --- a/wazo_dird/plugins/office365_backend/tests/test_office365_plugin.py +++ b/wazo_dird/plugins/office365_backend/tests/test_office365_plugin.py @@ -3,13 +3,7 @@ from unittest import TestCase -from hamcrest import ( - assert_that, - calling, - equal_to, - not_, - raises, -) +from hamcrest import assert_that, calling, equal_to, not_, raises from ..plugin import Office365Plugin @@ -18,9 +12,7 @@ class TestOffice365Plugin(TestCase): DEPENDENCIES = { 'config': { - 'auth': { - 'host': '9497', - }, + 'auth': {'host': '9497'}, 'endpoint': 'www.bros.com', 'name': 'office365', 'user_agent': 'luigi', @@ -31,7 +23,7 @@ class TestOffice365Plugin(TestCase): 'reverse': "{firstname} {lastname}", 'phone_mobile': "{mobile}", }, - }, + } } def setUp(self): @@ -40,7 +32,7 @@ def setUp(self): def test_load(self): assert_that( calling(self.source.load).with_args(self.DEPENDENCIES), - not_(raises(Exception)) + not_(raises(Exception)), ) def test_first_match_predicate(self): @@ -48,11 +40,7 @@ def test_first_match_predicate(self): term = '5555551234' - mario = { - 'name': 'Mario Bros', - 'mobilePhone': None, - 'businessPhones': [], - } + mario = {'name': 'Mario Bros', 'mobilePhone': None, 'businessPhones': []} luigi = { 'name': 'Luigi Bros', 'mobilePhone': None, @@ -67,4 +55,6 @@ def test_first_match_predicate(self): assert_that(self.source._first_match_predicate(term, mario), equal_to(False)) assert_that(self.source._first_match_predicate(term, luigi), equal_to(True)) assert_that(self.source._first_match_predicate(term, peach), equal_to(True)) - assert_that(self.source._first_match_predicate(term[:-1], peach), equal_to(False)) + assert_that( + self.source._first_match_predicate(term[:-1], peach), equal_to(False) + ) diff --git a/wazo_dird/plugins/personal/http.py b/wazo_dird/plugins/personal/http.py index 6242799d..e0084cde 100644 --- a/wazo_dird/plugins/personal/http.py +++ b/wazo_dird/plugins/personal/http.py @@ -41,11 +41,7 @@ def post(self): contact = self.personal_service.create_contact(contact, token_infos) return contact, 201 except self.personal_service.InvalidPersonalContact as e: - error = { - 'reason': e.errors, - 'timestamp': [time()], - 'status_code': 400, - } + error = {'reason': e.errors, 'timestamp': [time()], 'status_code': 400} return error, 400 except self.personal_service.DuplicatedContactException: error = { @@ -80,10 +76,7 @@ def delete(self): @classmethod def contacts_formatter(cls, mimetype): - formatters = { - 'text/csv': cls.format_csv, - 'application/json': cls.format_json - } + formatters = {'text/csv': cls.format_csv, 'application/json': cls.format_json} return formatters.get(mimetype, cls.format_json) @staticmethod @@ -91,7 +84,9 @@ def format_csv(contacts): if not contacts: return '', 204 csv_text = io.StringIO() - fieldnames = sorted(list(set(attribute for contact in contacts for attribute in contact))) + fieldnames = sorted( + list(set(attribute for contact in contacts for attribute in contact)) + ) for contact in contacts: for attribute in contact: if contact[attribute] is None: @@ -99,9 +94,11 @@ def format_csv(contacts): csv_writer = csv.DictWriter(csv_text, fieldnames) csv_writer.writeheader() csv_writer.writerows(contacts) - return Response(response=csv_text.getvalue(), - status=200, - content_type='text/csv; charset=utf-8') + return Response( + response=csv_text.getvalue(), + status=200, + content_type='text/csv; charset=utf-8', + ) @staticmethod def format_json(contacts): @@ -124,11 +121,7 @@ def get(self, contact_id): contact = self.personal_service.get_contact(contact_id, token_infos) return contact, 200 except self.personal_service.NoSuchContact as e: - error = { - 'reason': [str(e)], - 'timestamp': [time()], - 'status_code': 404, - } + error = {'reason': [str(e)], 'timestamp': [time()], 'status_code': 404} return error, 404 @required_acl('dird.personal.{contact_id}.update') @@ -137,21 +130,15 @@ def put(self, contact_id): token_infos = auth.client().token.get(token) new_contact = request.json try: - contact = self.personal_service.edit_contact(contact_id, new_contact, token_infos) + contact = self.personal_service.edit_contact( + contact_id, new_contact, token_infos + ) return contact, 200 except self.personal_service.NoSuchContact as e: - error = { - 'reason': [str(e)], - 'timestamp': [time()], - 'status_code': 404, - } + error = {'reason': [str(e)], 'timestamp': [time()], 'status_code': 404} return error, 404 except self.personal_service.InvalidPersonalContact as e: - error = { - 'reason': e.errors, - 'timestamp': [time()], - 'status_code': 400, - } + error = {'reason': e.errors, 'timestamp': [time()], 'status_code': 400} return error, 400 except self.personal_service.DuplicatedContactException: error = { @@ -169,11 +156,7 @@ def delete(self, contact_id): self.personal_service.remove_contact(contact_id, token_infos) return '', 204 except self.personal_service.NoSuchContact as e: - error = { - 'reason': [str(e)], - 'timestamp': [time()], - 'status_code': 404, - } + error = {'reason': [str(e)], 'timestamp': [time()], 'status_code': 404} return error, 404 @@ -194,11 +177,7 @@ def post(self): try: csv_document = request.data.decode(charset) except UnicodeDecodeError as e: - error = { - 'reason': [str(e)], - 'timestamp': [time()], - 'status_code': 400, - } + error = {'reason': [str(e)], 'timestamp': [time()], 'status_code': 400} return error, 400 created, errors = self._mass_import(csv_document, token_infos) @@ -211,10 +190,7 @@ def post(self): } return error, 400 - result = { - 'created': created, - 'failed': errors, - } + result = {'created': created, 'failed': errors} return result, 201 def _mass_import(self, csv_document, token_infos): diff --git a/wazo_dird/plugins/personal/plugin.py b/wazo_dird/plugins/personal/plugin.py index d86f5947..70ad8280 100644 --- a/wazo_dird/plugins/personal/plugin.py +++ b/wazo_dird/plugins/personal/plugin.py @@ -6,11 +6,7 @@ from wazo_dird import BaseViewPlugin -from .http import ( - PersonalAll, - PersonalImport, - PersonalOne, -) +from .http import PersonalAll, PersonalImport, PersonalOne logger = logging.getLogger(__name__) diff --git a/wazo_dird/plugins/personal/tests/test_personal_view.py b/wazo_dird/plugins/personal/tests/test_personal_view.py index cc0860a5..aaac0341 100644 --- a/wazo_dird/plugins/personal/tests/test_personal_view.py +++ b/wazo_dird/plugins/personal/tests/test_personal_view.py @@ -7,31 +7,24 @@ from mock import Mock from ..plugin import PersonalViewPlugin -from ..http import ( - PersonalAll, - PersonalImport, - PersonalOne, -) +from ..http import PersonalAll, PersonalImport, PersonalOne class TestPersonalView(TestCase): - def setUp(self): self.plugin = PersonalViewPlugin() self.api = Mock() def test_that_load_with_no_personal_service_does_not_add_routes(self): - self.plugin.load({'config': {}, - 'http_namespace': Mock(), - 'api': self.api, - 'services': {}}) + self.plugin.load( + {'config': {}, 'http_namespace': Mock(), 'api': self.api, 'services': {}} + ) assert_that(self.api.add_resource.call_count, equal_to(0)) def test_that_load_adds_the_routes(self): args = { - 'config': {'displays': {}, - 'profile_to_display': {}}, + 'config': {'displays': {}, 'profile_to_display': {}}, 'http_namespace': Mock(), 'api': self.api, 'services': {'personal': Mock()}, @@ -40,14 +33,11 @@ def test_that_load_adds_the_routes(self): self.plugin.load(args) self.api.add_resource.assert_any_call( - PersonalAll, - PersonalViewPlugin.personal_all_url, + PersonalAll, PersonalViewPlugin.personal_all_url ) self.api.add_resource.assert_any_call( - PersonalOne, - PersonalViewPlugin.personal_one_url, + PersonalOne, PersonalViewPlugin.personal_one_url ) self.api.add_resource.assert_any_call( - PersonalImport, - PersonalViewPlugin.personal_import_url, + PersonalImport, PersonalViewPlugin.personal_import_url ) diff --git a/wazo_dird/plugins/personal_backend/http.py b/wazo_dird/plugins/personal_backend/http.py index cbba7b9d..b3ad4a87 100644 --- a/wazo_dird/plugins/personal_backend/http.py +++ b/wazo_dird/plugins/personal_backend/http.py @@ -3,16 +3,9 @@ from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) - -from .schemas import ( - list_schema, - source_schema, - source_list_schema, -) +from wazo_dird.helpers import SourceItem, SourceList + +from .schemas import list_schema, source_schema, source_list_schema class PersonalList(SourceList): diff --git a/wazo_dird/plugins/personal_backend/plugin.py b/wazo_dird/plugins/personal_backend/plugin.py index 2b82e357..959eef34 100644 --- a/wazo_dird/plugins/personal_backend/plugin.py +++ b/wazo_dird/plugins/personal_backend/plugin.py @@ -22,7 +22,6 @@ class PersonalView(BaseBackendView): class PersonalBackend(BaseSourcePlugin): - def load(self, config, search_engine=None): logger.debug('Loading personal source') @@ -36,9 +35,11 @@ def load(self, config, search_engine=None): unique_column, format_columns, is_personal=True, - is_deletable=True + is_deletable=True, + ) + self._SourceResult = lambda contact: result_class( + self._remove_empty_values(contact) ) - self._SourceResult = lambda contact: result_class(self._remove_empty_values(contact)) self._search_engine = search_engine or self._new_search_engine( config['config'].get(self.SEARCHED_COLUMNS), config['config'].get(self.FIRST_MATCHED_COLUMNS), @@ -53,14 +54,18 @@ def search(self, term, args=None): def first_match(self, term, args=None): logger.debug('First matching personal contacts with %s', term) user_uuid = args['xivo_user_uuid'] - matching_contacts = self._search_engine.find_first_personal_contact(user_uuid, term) + matching_contacts = self._search_engine.find_first_personal_contact( + user_uuid, term + ) for contact in self.format_contacts(matching_contacts): return contact def list(self, source_entry_ids, args): logger.debug('Listing personal contacts: %s', source_entry_ids) user_uuid = args['token_infos']['xivo_user_uuid'] - matching_contacts = self._search_engine.list_personal_contacts(user_uuid, source_entry_ids) + matching_contacts = self._search_engine.list_personal_contacts( + user_uuid, source_entry_ids + ) return self.format_contacts(matching_contacts) def format_contacts(self, contacts): @@ -68,9 +73,7 @@ def format_contacts(self, contacts): def _new_search_engine(self, searched_columns, first_match_columns): return database.PersonalContactSearchEngine( - Session, - searched_columns, - first_match_columns, + Session, searched_columns, first_match_columns ) @staticmethod diff --git a/wazo_dird/plugins/personal_backend/tests/test_personal_backend.py b/wazo_dird/plugins/personal_backend/tests/test_personal_backend.py index a28c8d07..9f5b0b19 100644 --- a/wazo_dird/plugins/personal_backend/tests/test_personal_backend.py +++ b/wazo_dird/plugins/personal_backend/tests/test_personal_backend.py @@ -14,32 +14,37 @@ from ..plugin import PersonalBackend SOME_UUID = str(uuid4()) -CONTACT_1 = {'id': str(uuid4()), - 'firstname': 'Foo'} +CONTACT_1 = {'id': str(uuid4()), 'firstname': 'Foo'} CONTACT_2 = {'firstname': 'Bar'} class TestPersonalBackend(TestCase): - def setUp(self): self._source = PersonalBackend() self._search_engine = Mock(database.PersonalContactSearchEngine) - self._source.load({'config': {'name': 'personal'}}, search_engine=self._search_engine) + self._source.load( + {'config': {'name': 'personal'}}, search_engine=self._search_engine + ) def test_that_list_calls_list_on_the_search_engine(self): ids = ['1', '2'] self._search_engine.list_personal_contacts.return_value = [CONTACT_1, CONTACT_2] - self._source.list(ids, {'token_infos': {'token': 'valid-token', - 'xivo_user_uuid': SOME_UUID}}) + self._source.list( + ids, {'token_infos': {'token': 'valid-token', 'xivo_user_uuid': SOME_UUID}} + ) - self._search_engine.list_personal_contacts.assert_called_once_with(SOME_UUID, ids) + self._search_engine.list_personal_contacts.assert_called_once_with( + SOME_UUID, ids + ) def test_that_list_sets_attribute_personal_and_deletable(self): self._search_engine.list_personal_contacts.return_value = [CONTACT_1] - result = self._source.list(['1'], {'token_infos': {'token': 'valid-token', - 'xivo_user_uuid': SOME_UUID}}) + result = self._source.list( + ['1'], + {'token_infos': {'token': 'valid-token', 'xivo_user_uuid': SOME_UUID}}, + ) assert_that(result, has_item(has_property('is_personal', True))) assert_that(result, has_item(has_property('is_deletable', True))) @@ -47,25 +52,34 @@ def test_that_list_sets_attribute_personal_and_deletable(self): def test_that_search_calls_find_personal_contacts(self): self._search_engine.find_personal_contacts.return_value = [CONTACT_1] - self._source.search('alice', {'token': 'valid-token', - 'xivo_user_uuid': SOME_UUID}) + self._source.search( + 'alice', {'token': 'valid-token', 'xivo_user_uuid': SOME_UUID} + ) - self._search_engine.find_personal_contacts.assert_called_once_with(SOME_UUID, 'alice') + self._search_engine.find_personal_contacts.assert_called_once_with( + SOME_UUID, 'alice' + ) def test_that_first_match_calls_find_first_personal_contact(self): self._search_engine.find_first_personal_contact.return_value = [CONTACT_1] - result = self._source.first_match('555', {'token': 'valid-token', - 'xivo_user_uuid': SOME_UUID}) + result = self._source.first_match( + '555', {'token': 'valid-token', 'xivo_user_uuid': SOME_UUID} + ) - self._search_engine.find_first_personal_contact.assert_called_once_with(SOME_UUID, '555') + self._search_engine.find_first_personal_contact.assert_called_once_with( + SOME_UUID, '555' + ) assert_that(result.fields, equal_to(CONTACT_1)) def test_that_first_match_return_none_if_no_match(self): self._search_engine.find_first_personal_contact.return_value = [] - result = self._source.first_match('555', {'token': 'valid-token', - 'xivo_user_uuid': SOME_UUID}) + result = self._source.first_match( + '555', {'token': 'valid-token', 'xivo_user_uuid': SOME_UUID} + ) - self._search_engine.find_first_personal_contact.assert_called_once_with(SOME_UUID, '555') + self._search_engine.find_first_personal_contact.assert_called_once_with( + SOME_UUID, '555' + ) assert_that(result, equal_to(None)) diff --git a/wazo_dird/plugins/personal_service/plugin.py b/wazo_dird/plugins/personal_service/plugin.py index 60f19c4a..535c49e3 100644 --- a/wazo_dird/plugins/personal_service/plugin.py +++ b/wazo_dird/plugins/personal_service/plugin.py @@ -18,15 +18,16 @@ class PersonalImportError(ValueError): class PersonalServicePlugin(BaseServicePlugin): - def load(self, dependencies): try: config = dependencies['config'] source_manager = dependencies['source_manager'] controller = dependencies['controller'] except KeyError: - msg = ('%s should be loaded with "config" and "source_manager" but received: %s' - % (self.__class__.__name__, ','.join(dependencies.keys()))) + msg = ( + '%s should be loaded with "config" and "source_manager" but received: %s' + % (self.__class__.__name__, ','.join(dependencies.keys())) + ) raise ValueError(msg) crud = database.PersonalContactCRUD(Session) @@ -52,13 +53,15 @@ def __init__(self, config, source_manager, crud, controller): def create_contact(self, contact_infos, token_infos): self.validate_contact(contact_infos) - return self._crud.create_personal_contact(token_infos['xivo_user_uuid'], contact_infos) + return self._crud.create_personal_contact( + token_infos['xivo_user_uuid'], contact_infos + ) def create_contacts(self, contact_infos, token_infos): errors = [] to_add = [] existing_contact_uuids = set( - [contact['id'] for contact in self._crud.list_personal_contacts()], + [contact['id'] for contact in self._crud.list_personal_contacts()] ) for contact_info in contact_infos: @@ -75,15 +78,20 @@ def create_contacts(self, contact_infos, token_infos): except PersonalImportError as e: errors.append({'errors': [str(e)], 'line': contact_infos.line_num}) - return self._crud.create_personal_contacts(token_infos['xivo_user_uuid'], to_add), errors + return ( + self._crud.create_personal_contacts(token_infos['xivo_user_uuid'], to_add), + errors, + ) def get_contact(self, contact_id, token_infos): - return self._crud.get_personal_contact(token_infos['xivo_user_uuid'], contact_id) + return self._crud.get_personal_contact( + token_infos['xivo_user_uuid'], contact_id + ) def edit_contact(self, contact_id, contact_infos, token_infos): self.validate_contact(contact_infos) return self._crud.edit_personal_contact( - token_infos['xivo_user_uuid'], contact_id, contact_infos, + token_infos['xivo_user_uuid'], contact_id, contact_infos ) def remove_contact(self, contact_id, token_infos): diff --git a/wazo_dird/plugins/phone/http.py b/wazo_dird/plugins/phone/http.py index 5b55483b..307c650d 100644 --- a/wazo_dird/plugins/phone/http.py +++ b/wazo_dird/plugins/phone/http.py @@ -12,24 +12,17 @@ from requests.exceptions import HTTPError from wazo_dird.auth import required_acl -from wazo_dird.exception import ( - OldAPIException, - ProfileNotFoundError, - NoSuchUser, -) +from wazo_dird.exception import OldAPIException, ProfileNotFoundError, NoSuchUser from wazo_dird.rest_api import LegacyAuthResource logger = logging.getLogger(__name__) def _error(code, msg): - return {'reason': [msg], - 'timestamp': [time()], - 'status_code': code}, code + return {'reason': [msg], 'timestamp': [time()], 'status_code': code}, code class PhoneMenu(LegacyAuthResource): - def __init__(self, template, content_type): self.template = template self.content_type = content_type @@ -38,15 +31,14 @@ def __init__(self, template, content_type): def get(self, profile, xivo_user_uuid): proxy_url = request.headers.get('Proxy-URL', _build_next_url('menu')) - response_xml = render_template(self.template, - xivo_proxy_url=proxy_url, - xivo_user_uuid=xivo_user_uuid) + response_xml = render_template( + self.template, xivo_proxy_url=proxy_url, xivo_user_uuid=xivo_user_uuid + ) return Response(response_xml, content_type=self.content_type, status=200) class PhoneInput(LegacyAuthResource): - def __init__(self, template, content_type): self.template = template self.content_type = content_type @@ -55,18 +47,21 @@ def __init__(self, template, content_type): def get(self, profile, xivo_user_uuid): proxy_url = request.headers.get('Proxy-URL', _build_next_url('input')) - response_xml = render_template(self.template, - xivo_proxy_url=proxy_url, - xivo_user_uuid=xivo_user_uuid) + response_xml = render_template( + self.template, xivo_proxy_url=proxy_url, xivo_user_uuid=xivo_user_uuid + ) return Response(response_xml, content_type=self.content_type, status=200) class PhoneLookup(LegacyAuthResource): - def __init__( - self, template, content_type, phone_lookup_service, auth_client, - max_item_per_page=None, + self, + template, + content_type, + phone_lookup_service, + auth_client, + max_item_per_page=None, ): self.template = template self.content_type = content_type @@ -75,13 +70,17 @@ def __init__( self.parser = reqparse.RequestParser() self.parser.add_argument( - 'limit', type=natural, required=False, default=max_item_per_page, location='args', + 'limit', + type=natural, + required=False, + default=max_item_per_page, + location='args', ) self.parser.add_argument( - 'offset', type=natural, required=False, default=0, location='args', + 'offset', type=natural, required=False, default=0, location='args' ) self.parser.add_argument( - 'term', type=str, required=True, help='term is missing', location='args', + 'term', type=str, required=True, help='term is missing', location='args' ) @required_acl('dird.directories.lookup.{profile}.{xivo_user_uuid}.read') @@ -96,8 +95,7 @@ def get(self, profile, xivo_user_uuid): try: tenant_uuid = self._get_user_tenant_uuid(xivo_user_uuid) profile_config = self.phone_lookup_service.profile_service.get_by_name( - tenant_uuid, - profile, + tenant_uuid, profile ) except OldAPIException as e: logger.warning('%s', e.body['reason'][0]) @@ -115,18 +113,22 @@ def get(self, profile, xivo_user_uuid): ) except ProfileNotFoundError: logger.warning('phone lookup failed: unknown profile %r', profile) - return _error(404, 'The profile `{profile}` does not exist'.format(profile=profile)) - - response_xml = render_template(self.template, - results=results['results'], - xivo_proxy_url=proxy_url, - xivo_user_uuid=xivo_user_uuid, - term=term, - limit=limit, - total=results['total'], - offset=results['offset'], - offset_next=results['next_offset'], - offset_previous=results['previous_offset']) + return _error( + 404, 'The profile `{profile}` does not exist'.format(profile=profile) + ) + + response_xml = render_template( + self.template, + results=results['results'], + xivo_proxy_url=proxy_url, + xivo_user_uuid=xivo_user_uuid, + term=term, + limit=limit, + total=results['total'], + offset=results['offset'], + offset_next=results['next_offset'], + offset_previous=results['previous_offset'], + ) return Response(response_xml, content_type=self.content_type, status=200) diff --git a/wazo_dird/plugins/phone/tests/test_phone_view.py b/wazo_dird/plugins/phone/tests/test_phone_view.py index 9b0e5d33..ac7d0f96 100644 --- a/wazo_dird/plugins/phone/tests/test_phone_view.py +++ b/wazo_dird/plugins/phone/tests/test_phone_view.py @@ -11,7 +11,6 @@ @patch('wazo_dird.plugins.phone.http.request') class TestPhoneView(TestCase): - def test_that_build_next_url_return_input_url_when_is_menu(self, MockedRequest): url = 'http://127.0.0.1:9489/0.1/directories/{}/profile/vendor' expected_result = url.format('input') @@ -21,7 +20,7 @@ def test_that_build_next_url_return_input_url_when_is_menu(self, MockedRequest): assert_that(result, equal_to(expected_result)) def test_that_build_next_url_return_input_url_when_is_menu_with_profile_menu( - self, MockedRequest, + self, MockedRequest ): url = 'http://127.0.0.1:9489/0.1/directories/{}/menu/vendor' expected_result = url.format('input') @@ -39,7 +38,7 @@ def test_that_build_next_url_return_lookup_url_when_is_input(self, MockedRequest assert_that(result, equal_to(expected_result)) def test_that_build_next_url_return_lookup_url_when_is_input_with_profile_input( - self, MockedRequest, + self, MockedRequest ): url = 'http://127.0.0.1:9489/0.1/directories/{}/input/vendor' expected_result = url.format('lookup') diff --git a/wazo_dird/plugins/phone_helpers.py b/wazo_dird/plugins/phone_helpers.py index 983f19f5..d4a8ec31 100644 --- a/wazo_dird/plugins/phone_helpers.py +++ b/wazo_dird/plugins/phone_helpers.py @@ -22,13 +22,14 @@ def new_phone_lookup_service_from_args(dependencies): class _PhoneLookupService: - def __init__(self, lookup_service, display_service, profile_service): self._lookup_service = lookup_service self._display_service = display_service self.profile_service = profile_service - def lookup(self, profile_config, term, tenant_uuid, user_uuid, token, limit=None, offset=0): + def lookup( + self, profile_config, term, tenant_uuid, user_uuid, token, limit=None, offset=0 + ): display = profile_config['display'] formatter = _PhoneResultFormatter(display) @@ -44,7 +45,7 @@ def lookup(self, profile_config, term, tenant_uuid, user_uuid, token, limit=None formatted_results.sort(key=attrgetter('name', 'number')) if limit is not None: - paginated_result = formatted_results[offset:offset + limit] + paginated_result = formatted_results[offset : offset + limit] else: paginated_result = formatted_results[offset:] @@ -54,7 +55,7 @@ def lookup(self, profile_config, term, tenant_uuid, user_uuid, token, limit=None 'offset': offset, 'total': len(formatted_results), 'next_offset': self._next_offset(offset, limit, len(formatted_results)), - 'previous_offset': self._previous_offset(offset, limit) + 'previous_offset': self._previous_offset(offset, limit), } def _next_offset(self, offset, limit, results_count): @@ -122,7 +123,8 @@ def _extract_results(self, fields): except KeyError: logger.info( 'phone lookup found a result be could not format a name %s %s', - number_display, fields, + number_display, + fields, ) continue @@ -132,7 +134,7 @@ def _extract_number_from_pretty_number(self, pretty_number): number_with_parentheses = self._INVALID_CHARACTERS_REGEX.sub('', pretty_number) # Convert numbers +33(0)123456789 to 0033123456789 number_with_parentheses = self._SPECIAL_NUMBER_REGEX.sub( - r'00\1\2', number_with_parentheses, + r'00\1\2', number_with_parentheses ) return self._PARENTHESES_REGEX.sub('', number_with_parentheses) @@ -142,6 +144,7 @@ def _extract_number_fields(display): return [] return [ - field for field in display['columns'] + field + for field in display['columns'] if field.get('type') == 'number' and field.get('field') ] diff --git a/wazo_dird/plugins/phonebook/http.py b/wazo_dird/plugins/phonebook/http.py index e2c4137c..89fb88e9 100644 --- a/wazo_dird/plugins/phonebook/http.py +++ b/wazo_dird/plugins/phonebook/http.py @@ -28,15 +28,13 @@ def _make_error(reason, status_code): - return { - 'reason': [reason], - 'timestamp': [time.time()], - 'status_code': status_code, - }, status_code + return ( + {'reason': [reason], 'timestamp': [time.time()], 'status_code': status_code}, + status_code, + ) class _Resource(LegacyAuthResource): - def __init__(self, phonebook_service, auth_client): self.phonebook_service = phonebook_service self._auth_client = auth_client @@ -49,11 +47,10 @@ def _find_tenant(self, scoping_tenant, name): class _ArgParser: - def __init__(self, args, valid_columns=None): self._search = args.get('search') self._direction = self._get_string_from_valid_values( - args, 'direction', ['asc', 'desc', None], + args, 'direction', ['asc', 'desc', None] ) self._limit = self._get_positive_int(args, 'limit') self._offset = self._get_positive_int(args, 'offset') @@ -104,7 +101,6 @@ def _get_positive_int(args, name): def _default_error_route(f): - @wraps(f) def decorator(self_, *args, **kwargs): try: @@ -114,6 +110,7 @@ def decorator(self_, *args, **kwargs): logger.debug('%s', traceback.format_exc()) code = self_.error_code_map.get(e.__class__) return _make_error(str(e), code) + return decorator @@ -133,11 +130,12 @@ class ContactAll(_Resource): def post(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.create_contact( - matching_tenant['uuid'], - phonebook_id, - request.json, - ), 201 + return ( + self.phonebook_service.create_contact( + matching_tenant['uuid'], phonebook_id, request.json + ), + 201, + ) @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.read') @_default_error_route @@ -146,20 +144,13 @@ def get(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) count = self.phonebook_service.count_contact( - matching_tenant['uuid'], - phonebook_id, - **parser.count_params() + matching_tenant['uuid'], phonebook_id, **parser.count_params() ) contacts = self.phonebook_service.list_contact( - matching_tenant['uuid'], - phonebook_id, - **parser.list_params() + matching_tenant['uuid'], phonebook_id, **parser.list_params() ) - return { - 'items': contacts, - 'total': count, - }, 200 + return {'items': contacts, 'total': count}, 200 class PhonebookAll(_Resource): @@ -180,36 +171,30 @@ def get(self, tenant): parser = _ArgParser(request.args, valid_columns=['name', 'description']) count = self.phonebook_service.count_phonebook( - matching_tenant['uuid'], - **parser.count_params() + matching_tenant['uuid'], **parser.count_params() ) phonebooks = self.phonebook_service.list_phonebook( - matching_tenant['uuid'], - **parser.list_params() + matching_tenant['uuid'], **parser.list_params() ) - return { - 'items': phonebooks, - 'total': count, - } + return {'items': phonebooks, 'total': count} @required_acl('dird.tenants.{tenant}.phonebooks.create') @_default_error_route def post(self, tenant): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.create_phonebook( - matching_tenant['uuid'], - request.json, - ), 201 + return ( + self.phonebook_service.create_phonebook( + matching_tenant['uuid'], request.json + ), + 201, + ) class ContactImport(_Resource): - error_code_map = { - NoSuchTenant: 404, - NoSuchPhonebook: 404, - } + error_code_map = {NoSuchTenant: 404, NoSuchPhonebook: 404} @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.create') @_default_error_route @@ -233,9 +218,7 @@ def post(self, tenant, phonebook_id): to_add = [c for c in csv.DictReader(data)] created, failed = self.phonebook_service.import_contacts( - matching_tenant['uuid'], - phonebook_id, - to_add, + matching_tenant['uuid'], phonebook_id, to_add ) return {'created': created, 'failed': failed} @@ -252,40 +235,45 @@ class ContactOne(_Resource): NoSuchTenant: 404, } - @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.read') + @required_acl( + 'dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.read' + ) @_default_error_route def get(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.get_contact( - matching_tenant['uuid'], - phonebook_id, - contact_uuid, - ), 200 + return ( + self.phonebook_service.get_contact( + matching_tenant['uuid'], phonebook_id, contact_uuid + ), + 200, + ) - @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.delete') + @required_acl( + 'dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.delete' + ) @_default_error_route def delete(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) self.phonebook_service.delete_contact( - matching_tenant['uuid'], - phonebook_id, - contact_uuid, + matching_tenant['uuid'], phonebook_id, contact_uuid ) return '', 204 - @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.update') + @required_acl( + 'dird.tenants.{tenant}.phonebooks.{phonebook_id}.contacts.{contact_uuid}.update' + ) @_default_error_route def put(self, tenant, phonebook_id, contact_uuid): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.edit_contact( - matching_tenant['uuid'], - phonebook_id, - contact_uuid, - request.json, - ), 200 + return ( + self.phonebook_service.edit_contact( + matching_tenant['uuid'], phonebook_id, contact_uuid, request.json + ), + 200, + ) class PhonebookOne(_Resource): @@ -311,15 +299,19 @@ def delete(self, tenant, phonebook_id): def get(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.get_phonebook(matching_tenant['uuid'], phonebook_id), 200 + return ( + self.phonebook_service.get_phonebook(matching_tenant['uuid'], phonebook_id), + 200, + ) @required_acl('dird.tenants.{tenant}.phonebooks.{phonebook_id}.update') @_default_error_route def put(self, tenant, phonebook_id): scoping_tenant = Tenant.autodetect() matching_tenant = self._find_tenant(scoping_tenant, tenant) - return self.phonebook_service.edit_phonebook( - matching_tenant['uuid'], - phonebook_id, - request.json, - ), 200 + return ( + self.phonebook_service.edit_phonebook( + matching_tenant['uuid'], phonebook_id, request.json + ), + 200, + ) diff --git a/wazo_dird/plugins/phonebook/plugin.py b/wazo_dird/plugins/phonebook/plugin.py index f4bac3a9..b1dd4ba8 100644 --- a/wazo_dird/plugins/phonebook/plugin.py +++ b/wazo_dird/plugins/phonebook/plugin.py @@ -3,23 +3,13 @@ from wazo_dird import BaseViewPlugin -from .http import ( - ContactAll, - ContactImport, - ContactOne, - PhonebookAll, - PhonebookOne, -) +from .http import ContactAll, ContactImport, ContactOne, PhonebookAll, PhonebookOne class PhonebookViewPlugin(BaseViewPlugin): - def load(self, dependencies=None): api = dependencies['api'] - args = ( - dependencies['services'].get('phonebook'), - dependencies['auth_client'], - ) + args = (dependencies['services'].get('phonebook'), dependencies['auth_client']) api.add_resource( ContactAll, diff --git a/wazo_dird/plugins/phonebook_backend/http.py b/wazo_dird/plugins/phonebook_backend/http.py index f3546626..12b6c980 100644 --- a/wazo_dird/plugins/phonebook_backend/http.py +++ b/wazo_dird/plugins/phonebook_backend/http.py @@ -3,16 +3,9 @@ from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) - -from .schemas import ( - list_schema, - source_schema, - source_list_schema, -) +from wazo_dird.helpers import SourceItem, SourceList + +from .schemas import list_schema, source_schema, source_list_schema class PhonebookList(SourceList): diff --git a/wazo_dird/plugins/phonebook_backend/plugin.py b/wazo_dird/plugins/phonebook_backend/plugin.py index 650ec045..4dd976ad 100644 --- a/wazo_dird/plugins/phonebook_backend/plugin.py +++ b/wazo_dird/plugins/phonebook_backend/plugin.py @@ -22,7 +22,6 @@ class PhonebookView(BaseBackendView): class PhonebookPlugin(BaseSourcePlugin): - def __init__(self, *args, **kwargs): self._crud = None self._source_name = None @@ -47,10 +46,7 @@ def load(self, dependencies): ) self._SourceResult = make_result_class( - 'phonebook', - self._source_name, - unique_column, - format_columns + 'phonebook', self._source_name, unique_column, format_columns ) logger.info('%s loaded', self._source_name) @@ -94,5 +90,7 @@ def _get_phonebook_id(self, tenant_uuid, config): if phonebook['name'] == phonebook_name: return phonebook['id'] - raise InvalidConfigError('sources/{}/phonebook_name'.format(self._source_name), - 'unknown phonebook {}'.format(phonebook_name)) + raise InvalidConfigError( + 'sources/{}/phonebook_name'.format(self._source_name), + 'unknown phonebook {}'.format(phonebook_name), + ) diff --git a/wazo_dird/plugins/phonebook_backend/tests/test_dird_phonebook_backend.py b/wazo_dird/plugins/phonebook_backend/tests/test_dird_phonebook_backend.py index 4c47336e..dbfdd749 100644 --- a/wazo_dird/plugins/phonebook_backend/tests/test_dird_phonebook_backend.py +++ b/wazo_dird/plugins/phonebook_backend/tests/test_dird_phonebook_backend.py @@ -6,17 +6,15 @@ from hamcrest import assert_that, equal_to from mock import Mock, patch, sentinel as s -from ..plugin import ( - PhonebookPlugin, - make_result_class -) +from ..plugin import PhonebookPlugin, make_result_class class TestDirdPhonebook(unittest.TestCase): - def setUp(self): self.source = PhonebookPlugin() - self.SourceResult = self.source._SourceResult = make_result_class('test', 'id', {}) + self.SourceResult = self.source._SourceResult = make_result_class( + 'test', 'id', {} + ) self.engine = self.source._search_engine = Mock() def test_that_the_id_is_used_if_supplied(self): @@ -27,14 +25,18 @@ def test_that_the_id_is_used_if_supplied(self): def test_with_an_existing_phonebook_by_name(self): phonebooks = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}] - with patch.object(self.source, '_crud', Mock(list=Mock(return_value=phonebooks))): + with patch.object( + self.source, '_crud', Mock(list=Mock(return_value=phonebooks)) + ): id_ = self.source._get_phonebook_id(s.tenant_uuid, {'name': 'bar'}) assert_that(id_, equal_to(2)) def test_that_find_first_returns_a_formated_result(self): - raw_result = self.engine.find_first_contact.return_value = {'id': 42, - 'name': 'foobar'} + raw_result = self.engine.find_first_contact.return_value = { + 'id': 42, + 'name': 'foobar', + } result = self.source.first_match(s.term) diff --git a/wazo_dird/plugins/phonebook_service/plugin.py b/wazo_dird/plugins/phonebook_service/plugin.py index 06a088ea..73178b59 100644 --- a/wazo_dird/plugins/phonebook_service/plugin.py +++ b/wazo_dird/plugins/phonebook_service/plugin.py @@ -9,10 +9,7 @@ from wazo_dird import BaseServicePlugin from wazo_dird import database from wazo_dird.database.helpers import Session -from wazo_dird.exception import ( - InvalidContactException, - InvalidPhonebookException, -) +from wazo_dird.exception import InvalidContactException, InvalidPhonebookException logger = logging.getLogger(__name__) @@ -27,13 +24,11 @@ def ensure_dict(self, data): class PhonebookServicePlugin(BaseServicePlugin): - def load(self, args): self._config = args.get('config') if not self._config: msg = '{} should be loaded with "config" but received: {}'.format( - self.__class__.__name__, - ','.join(args.keys()), + self.__class__.__name__, ','.join(args.keys()) ) raise ValueError(msg) @@ -45,18 +40,27 @@ def load(self, args): class _PhonebookService: - def __init__(self, phonebook_crud, contact_crud, tenant_crud): self._phonebook_crud = phonebook_crud self._contact_crud = contact_crud self._tenant_crud = tenant_crud - def list_contact(self, tenant_uuid, phonebook_id, limit=None, offset=None, - order=None, direction=None, **params): + def list_contact( + self, + tenant_uuid, + phonebook_id, + limit=None, + offset=None, + order=None, + direction=None, + **params + ): results = self._contact_crud.list(tenant_uuid, phonebook_id, **params) if order: reverse = direction == 'desc' - results = sorted(results, key=lambda x: unidecode(x.get(order, '')), reverse=reverse) + results = sorted( + results, key=lambda x: unidecode(x.get(order, '')), reverse=reverse + ) if offset: results = results[offset:] if limit: @@ -116,7 +120,9 @@ def import_contacts(self, tenant_uuid, phonebook_id, contacts): except InvalidContactException: errors.append(contact) - created, failed = self._contact_crud.create_many(tenant_uuid, phonebook_id, to_add) + created, failed = self._contact_crud.create_many( + tenant_uuid, phonebook_id, to_add + ) return created, failed + errors diff --git a/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py b/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py index cca66724..cf025127 100644 --- a/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py +++ b/wazo_dird/plugins/phonebook_service/tests/test_phonebook_service.py @@ -3,55 +3,42 @@ import unittest -from hamcrest import (assert_that, - calling, - contains, - contains_inanyorder, - equal_to, - raises) +from hamcrest import ( + assert_that, + calling, + contains, + contains_inanyorder, + equal_to, + raises, +) from mock import Mock, sentinel as s from wazo_dird import database -from wazo_dird.exception import ( - InvalidContactException, - InvalidPhonebookException, -) +from wazo_dird.exception import InvalidContactException, InvalidPhonebookException -from ..plugin import ( - PhonebookServicePlugin as Plugin, - _PhonebookService as Service, -) +from ..plugin import PhonebookServicePlugin as Plugin, _PhonebookService as Service class TestPhonebookServicePlugin(unittest.TestCase): - def setUp(self): self.args = {'config': {}} def test_that_loading_without_a_proper_config_raises(self): plugin = Plugin() - assert_that(calling(plugin.load).with_args({}), - raises(ValueError)) - assert_that(calling(plugin.load).with_args({'config': {}}), - raises(ValueError)) + assert_that(calling(plugin.load).with_args({}), raises(ValueError)) + assert_that(calling(plugin.load).with_args({'config': {}}), raises(ValueError)) class _BasePhonebookServiceTest(unittest.TestCase): - def setUp(self): self.phonebook_crud = Mock(database.PhonebookCRUD) self.contact_crud = Mock(database.PhonebookContactCRUD) self.tenant_crud = Mock(database.TenantCRUD) - self.service = Service( - self.phonebook_crud, - self.contact_crud, - self.tenant_crud, - ) + self.service = Service(self.phonebook_crud, self.contact_crud, self.tenant_crud) class TestPhonebookPhonebookAPI(_BasePhonebookServiceTest): - def test_list_phonebook(self): result = self.service.list_phonebook(s.tenant_uuid) @@ -68,7 +55,9 @@ def test_create_phonebook(self): def test_count_phonebook(self): result = self.service.count_phonebook(s.tenant_uuid, param1=s.param1) - self.phonebook_crud.count.assert_called_once_with(s.tenant_uuid, param1=s.param1) + self.phonebook_crud.count.assert_called_once_with( + s.tenant_uuid, param1=s.param1 + ) assert_that(result, equal_to(self.phonebook_crud.count.return_value)) def test_that_create_with_no_name_raises(self): @@ -77,7 +66,7 @@ def test_that_create_with_no_name_raises(self): assert_that( calling(self.service.create_phonebook).with_args(s.tenant_uuid, body), raises(InvalidPhonebookException), - body + body, ) def test_edit_phonebook(self): @@ -85,7 +74,9 @@ def test_edit_phonebook(self): result = self.service.edit_phonebook(s.tenant_uuid, s.phonebook_id, body) - self.phonebook_crud.edit.assert_called_once_with(s.tenant_uuid, s.phonebook_id, body) + self.phonebook_crud.edit.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, body + ) assert_that(result, equal_to(self.phonebook_crud.edit.return_value)) def test_that_edit_with_no_name_raises(self): @@ -93,7 +84,7 @@ def test_that_edit_with_no_name_raises(self): for body in bodies: assert_that( calling(self.service.edit_phonebook).with_args( - s.tenant_uuid, s.phonebook_id, body, + s.tenant_uuid, s.phonebook_id, body ), raises(InvalidPhonebookException), body, @@ -102,7 +93,9 @@ def test_that_edit_with_no_name_raises(self): def test_delete_phonebook(self): self.service.delete_phonebook(s.tenant_uuid, s.phonebook_id) - self.phonebook_crud.delete.assert_called_once_with(s.tenant_uuid, s.phonebook_id) + self.phonebook_crud.delete.assert_called_once_with( + s.tenant_uuid, s.phonebook_id + ) def test_get_phonebook(self): result = self.service.get_phonebook(s.tenant_uuid, s.phonebook_id) @@ -112,7 +105,6 @@ def test_get_phonebook(self): class TestPhonebookServiceContactAPI(_BasePhonebookServiceTest): - def test_count_contact(self): result = self.service.count_contact(s.tenant_uuid, s.phonebook_id) @@ -120,13 +112,13 @@ def test_count_contact(self): self.contact_crud.count.assert_called_once_with(s.tenant_uuid, s.phonebook_id) def test_count_contact_with_a_search_param(self): - result = self.service.count_contact(s.tenant_uuid, s.phonebook_id, search=s.search) + result = self.service.count_contact( + s.tenant_uuid, s.phonebook_id, search=s.search + ) assert_that(result, equal_to(self.contact_crud.count.return_value)) self.contact_crud.count.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search ) def test_create_contact(self): @@ -135,20 +127,18 @@ def test_create_contact(self): result = self.service.create_contact(s.tenant_uuid, s.phonebook_id, body) assert_that(result, equal_to(self.contact_crud.create.return_value)) - self.contact_crud.create.assert_called_once_with(s.tenant_uuid, s.phonebook_id, body) + self.contact_crud.create.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, body + ) def test_that_the_id_field_should_be_ignored_on_create(self): result = self.service.create_contact( - s.tenant_uuid, - s.phonebook_id, - {'firstname': 'bob', 'id': s.uuid}, + s.tenant_uuid, s.phonebook_id, {'firstname': 'bob', 'id': s.uuid} ) assert_that(result, equal_to(self.contact_crud.create.return_value)) self.contact_crud.create.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - {'firstname': 'bob'}, + s.tenant_uuid, s.phonebook_id, {'firstname': 'bob'} ) def test_that_create_contact_raises_for_invalid_input(self): @@ -156,7 +146,7 @@ def test_that_create_contact_raises_for_invalid_input(self): for body in invalid_bodies: assert_that( calling(self.service.create_contact).with_args( - s.tenant_uuid, s.phonebook_id, body, + s.tenant_uuid, s.phonebook_id, body ), raises(InvalidContactException), body, @@ -164,14 +154,13 @@ def test_that_create_contact_raises_for_invalid_input(self): def test_edit_contact(self): body = {'firstname': 'Foobar'} - result = self.service.edit_contact(s.tenant_uuid, s.phonebook_id, s.contact_uuid, body) + result = self.service.edit_contact( + s.tenant_uuid, s.phonebook_id, s.contact_uuid, body + ) assert_that(result, equal_to(self.contact_crud.edit.return_value)) self.contact_crud.edit.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - s.contact_uuid, - body, + s.tenant_uuid, s.phonebook_id, s.contact_uuid, body ) def test_that_edit_contact_ignores_the_id_field(self): @@ -184,31 +173,28 @@ def test_that_edit_contact_ignores_the_id_field(self): assert_that(result, equal_to(self.contact_crud.edit.return_value)) self.contact_crud.edit.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - s.contact_uuid, - {'firstname': 'alice'}, + s.tenant_uuid, s.phonebook_id, s.contact_uuid, {'firstname': 'alice'} ) def test_that_edit_contact_raises_for_invalid_input(self): invalid_bodies = [{'': 'Foo'}, {}] for body in invalid_bodies: assert_that( - calling( - self.service.edit_contact - ).with_args(s.tenant_uuid, s.phonebook_id, s.contact_uuid, body), + calling(self.service.edit_contact).with_args( + s.tenant_uuid, s.phonebook_id, s.contact_uuid, body + ), raises(InvalidContactException), - body + body, ) def test_delete_contact(self): - result = self.service.delete_contact(s.tenant_uuid, s.phonebook_id, s.contact_uuid) + result = self.service.delete_contact( + s.tenant_uuid, s.phonebook_id, s.contact_uuid + ) assert_that(result, equal_to(self.contact_crud.delete.return_value)) self.contact_crud.delete.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - s.contact_uuid, + s.tenant_uuid, s.phonebook_id, s.contact_uuid ) def test_get_contact(self): @@ -216,12 +202,11 @@ def test_get_contact(self): assert_that(result, equal_to(self.contact_crud.get.return_value)) self.contact_crud.get.assert_called_once_with( - s.tenant_uuid, s.phonebook_id, s.contact_uuid, + s.tenant_uuid, s.phonebook_id, s.contact_uuid ) class TestPhonebookServiceContactList(_BasePhonebookServiceTest): - def setUp(self): super().setUp() self._manolo = { @@ -229,35 +214,47 @@ def setUp(self): 'lastname': 'Laporte-Carpentier', 'number': '5551111234', } - self._annabelle = {'firstname': 'Ännabelle', 'lastname': 'Courval', 'number': '5552221234'} + self._annabelle = { + 'firstname': 'Ännabelle', + 'lastname': 'Courval', + 'number': '5552221234', + } self._gary_bob = {'firstname': 'Gary-Bob', 'lastname': 'Derome'} - self._antonin = {'firstname': 'Antonin', 'lastname': 'Mongeau', 'number': '5554441234'} + self._antonin = { + 'firstname': 'Antonin', + 'lastname': 'Mongeau', + 'number': '5554441234', + } self._simon = {'firstname': 'Simon', 'lastname': "L'Espérance"} self._contacts = [ - self._manolo, self._annabelle, self._gary_bob, self._antonin, self._simon, + self._manolo, + self._annabelle, + self._gary_bob, + self._antonin, + self._simon, ] def test_that_list_returns_the_db_result_when_no_pagination_or_sorting(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, search=s.search) + result = self.service.list_contact( + s.tenant_uuid, s.phonebook_id, search=s.search + ) self.contact_crud.list.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search ) assert_that(result, contains(*self._contacts)) def test_that_list_can_be_limited(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, search=s.search, limit=2) + result = self.service.list_contact( + s.tenant_uuid, s.phonebook_id, search=s.search, limit=2 + ) self.contact_crud.list.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search ) assert_that(result, contains(self._manolo, self._annabelle)) @@ -265,13 +262,11 @@ def test_that_list_can_have_an_offset(self): self.contact_crud.list.return_value = self._contacts result = self.service.list_contact( - s.tenant_uuid, s.phonebook_id, search=s.search, offset=3, + s.tenant_uuid, s.phonebook_id, search=s.search, offset=3 ) self.contact_crud.list.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search ) assert_that(result, contains(self._antonin, self._simon)) @@ -279,17 +274,11 @@ def test_that_limit_and_offset_work_togeter(self): self.contact_crud.list.return_value = self._contacts result = self.service.list_contact( - s.tenant_uuid, - s.phonebook_id, - search=s.search, - offset=1, - limit=2, + s.tenant_uuid, s.phonebook_id, search=s.search, offset=1, limit=2 ) self.contact_crud.list.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search ) assert_that(result, contains(self._annabelle, self._gary_bob)) @@ -297,82 +286,102 @@ def test_that_results_can_be_ordered(self): self.contact_crud.list.return_value = self._contacts result = self.service.list_contact( - s.tenant_uuid, - s.phonebook_id, - search=s.search, - order='firstname', + s.tenant_uuid, s.phonebook_id, search=s.search, order='firstname' ) self.contact_crud.list.assert_called_once_with( - s.tenant_uuid, - s.phonebook_id, - search=s.search, + s.tenant_uuid, s.phonebook_id, search=s.search + ) + assert_that( + result, + contains( + self._annabelle, + self._antonin, + self._gary_bob, + self._manolo, + self._simon, + ), ) - assert_that(result, contains(self._annabelle, - self._antonin, - self._gary_bob, - self._manolo, - self._simon)) def test_that_results_can_be_ordered_by_an_unknown_column_with_no_effect(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, search=s.search, - order='number', direction='desc') - - self.contact_crud.list.assert_called_once_with( + result = self.service.list_contact( s.tenant_uuid, s.phonebook_id, search=s.search, + order='number', + direction='desc', + ) + + self.contact_crud.list.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, search=s.search ) - assert_that(result, contains_inanyorder(self._manolo, - self._antonin, - self._annabelle, - self._gary_bob, # no number - self._simon)) # no number + assert_that( + result, + contains_inanyorder( + self._manolo, + self._antonin, + self._annabelle, + self._gary_bob, # no number + self._simon, + ), + ) # no number def test_that_the_direction_can_be_specified(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, search=s.search, - order='firstname', direction='desc') - - self.contact_crud.list.assert_called_once_with( + result = self.service.list_contact( s.tenant_uuid, s.phonebook_id, search=s.search, + order='firstname', + direction='desc', + ) + + self.contact_crud.list.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, search=s.search + ) + assert_that( + result, + contains( + self._simon, + self._manolo, + self._gary_bob, + self._antonin, + self._annabelle, + ), ) - assert_that(result, contains(self._simon, - self._manolo, - self._gary_bob, - self._antonin, - self._annabelle)) def test_all(self): self.contact_crud.list.return_value = self._contacts - result = self.service.list_contact(s.tenant_uuid, s.phonebook_id, - search=s.search, - order='lastname', direction='desc', - limit=3, offset=1) - - self.contact_crud.list.assert_called_once_with( + result = self.service.list_contact( s.tenant_uuid, s.phonebook_id, search=s.search, + order='lastname', + direction='desc', + limit=3, + offset=1, + ) + + self.contact_crud.list.assert_called_once_with( + s.tenant_uuid, s.phonebook_id, search=s.search ) assert_that(result, contains(self._manolo, self._simon, self._gary_bob)) class TestPhonebookServiceContactImport(_BasePhonebookServiceTest): - def test_import_with_invalid_contacts(self): db_errors = [s.error_1, s.error_2] self.contact_crud.create_many.return_value = s.created, db_errors invalids = [None, {}, {'': 'test'}, {'firstname': 'Foo', None: ['extra']}] contacts = invalids + [{'firstname': 'Foo'}] - created, errors = self.service.import_contacts(s.tenant_uuid, s.phonebook_id, contacts) + created, errors = self.service.import_contacts( + s.tenant_uuid, s.phonebook_id, contacts + ) assert_that(created, equal_to(s.created)) assert_that(errors, contains_inanyorder(*db_errors + invalids)) diff --git a/wazo_dird/plugins/phonebook_tenant_modifier/http.py b/wazo_dird/plugins/phonebook_tenant_modifier/http.py index ace6248d..974a2fd7 100644 --- a/wazo_dird/plugins/phonebook_tenant_modifier/http.py +++ b/wazo_dird/plugins/phonebook_tenant_modifier/http.py @@ -8,7 +8,6 @@ class PhonebookMover(AuthResource): - def __init__(self, service): self._service = service diff --git a/wazo_dird/plugins/phonebook_tenant_modifier/plugin.py b/wazo_dird/plugins/phonebook_tenant_modifier/plugin.py index 3e3ff6cd..d7f0dd28 100644 --- a/wazo_dird/plugins/phonebook_tenant_modifier/plugin.py +++ b/wazo_dird/plugins/phonebook_tenant_modifier/plugin.py @@ -4,15 +4,11 @@ from wazo_dird import BaseViewPlugin from wazo_dird.rest_api import api -from . import ( - http, - service, -) +from . import http, service # This plugin is used for the tenant uuid migration between wazo-auth and dird class PhonebookTenantMoverPlugin(BaseViewPlugin): - def load(self, dependencies): tenant_mover_service = service.PhonebookMoverService() api.add_resource( diff --git a/wazo_dird/plugins/phonebook_tenant_modifier/service.py b/wazo_dird/plugins/phonebook_tenant_modifier/service.py index f5bacba7..35434ef4 100644 --- a/wazo_dird/plugins/phonebook_tenant_modifier/service.py +++ b/wazo_dird/plugins/phonebook_tenant_modifier/service.py @@ -10,7 +10,6 @@ class PhonebookMoverService: - def __init__(self): self._tenant_crud = database.TenantCRUD(Session) self._phonebook_crud = database.PhonebookCRUD(Session) @@ -24,7 +23,9 @@ def update_tenant_uuid(self, tenant_name, tenant_uuid): phonebooks = self._phonebook_crud.list(old_uuid) logger.info('updating %s phonebooks', len(phonebooks)) for phonebook in phonebooks: - self._phonebook_crud.update_tenant(old_uuid, phonebook['id'], tenant_uuid) + self._phonebook_crud.update_tenant( + old_uuid, phonebook['id'], tenant_uuid + ) logger.info('deleting tenant: %s', old_uuid) self._tenant_crud.delete(old_uuid) logger.info('done') diff --git a/wazo_dird/plugins/polycom/plugin.py b/wazo_dird/plugins/polycom/plugin.py index 7aa922c3..cf9e66d4 100644 --- a/wazo_dird/plugins/polycom/plugin.py +++ b/wazo_dird/plugins/polycom/plugin.py @@ -26,7 +26,8 @@ def load(self, dependencies): PhoneInput, self.polycom_input, endpoint='PolycomPhoneInput', - resource_class_args=(TEMPLATE_POLYCOM_INPUT, CONTENT_TYPE)) + resource_class_args=(TEMPLATE_POLYCOM_INPUT, CONTENT_TYPE), + ) api.add_resource( PhoneLookup, self.polycom_lookup, diff --git a/wazo_dird/plugins/profile_service/plugin.py b/wazo_dird/plugins/profile_service/plugin.py index cfc87493..ee9d5e16 100644 --- a/wazo_dird/plugins/profile_service/plugin.py +++ b/wazo_dird/plugins/profile_service/plugin.py @@ -13,14 +13,12 @@ class ProfileServicePlugin(BaseServicePlugin): - def load(self, dependencies): controller = dependencies['controller'] return _ProfileService(database.ProfileCRUD(Session), controller) class _ProfileService: - def __init__(self, crud, controller): self._profile_crud = crud self._controller = controller @@ -75,7 +73,9 @@ def get_sources_from_profile_name(self, tenant_uuid, profile_name, **list_params def list_(self, visible_tenants, **list_params): return self._profile_crud.list_(visible_tenants, **list_params) - def _paginate(self, sources, limit=None, offset=0, order='name', direction='asc', **ignored): + def _paginate( + self, sources, limit=None, offset=0, order='name', direction='asc', **ignored + ): selected_sources = [] reverse = direction != 'asc' @@ -88,7 +88,9 @@ def _paginate(self, sources, limit=None, offset=0, order='name', direction='asc' if limit is None: return list(islice(selected_sources, offset, None)) - def _filter_sources(self, sources, name=None, backend=None, uuid=None, search=None, **ignored): + def _filter_sources( + self, sources, name=None, backend=None, uuid=None, search=None, **ignored + ): filtered_sources = [] for source in sources: if name and source['name'] != name: @@ -110,10 +112,14 @@ def _filter_sources(self, sources, name=None, backend=None, uuid=None, search=No filtered_sources.append(source) return filtered_sources - def _count(self, sources, limit=None, offset=0, order=None, direction=None, **ignored): + def _count( + self, sources, limit=None, offset=0, order=None, direction=None, **ignored + ): return len(sources) - def _filtered(self, sources, limit=None, offset=0, order=None, direction=None, **ignored): + def _filtered( + self, sources, limit=None, offset=0, order=None, direction=None, **ignored + ): if limit: return limit else: diff --git a/wazo_dird/plugins/profile_sources/http.py b/wazo_dird/plugins/profile_sources/http.py index df11f055..64c7da3f 100644 --- a/wazo_dird/plugins/profile_sources/http.py +++ b/wazo_dird/plugins/profile_sources/http.py @@ -10,7 +10,6 @@ class SourceResource(AuthResource): - def __init__(self, profile_service): self._profile_service = profile_service @@ -20,13 +19,7 @@ def get(self, profile): tenant_uuid = Tenant.autodetect().uuid count, filtered, sources = self._profile_service.get_sources_from_profile_name( - tenant_uuid=tenant_uuid, - profile_name=profile, - **args + tenant_uuid=tenant_uuid, profile_name=profile, **args ) - return { - 'total': count, - 'filtered': filtered, - 'items': sources, - } + return {'total': count, 'filtered': filtered, 'items': sources} diff --git a/wazo_dird/plugins/profile_sources/plugin.py b/wazo_dird/plugins/profile_sources/plugin.py index 231d2681..c6092348 100644 --- a/wazo_dird/plugins/profile_sources/plugin.py +++ b/wazo_dird/plugins/profile_sources/plugin.py @@ -11,13 +11,10 @@ class SourceViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] profile_service = dependencies['services']['profile'] args = (profile_service,) api.add_resource( - SourceResource, - '/directories//sources', - resource_class_args=args, + SourceResource, '/directories//sources', resource_class_args=args ) diff --git a/wazo_dird/plugins/profile_sources/tests/test_source_plugin.py b/wazo_dird/plugins/profile_sources/tests/test_source_plugin.py index a3f4f691..5871879b 100644 --- a/wazo_dird/plugins/profile_sources/tests/test_source_plugin.py +++ b/wazo_dird/plugins/profile_sources/tests/test_source_plugin.py @@ -11,10 +11,7 @@ class TestSourcePlugin(TestCase): - DEPENDENCIES = { - 'api': Mock(), - 'services': {'profile': Mock()}, - } + DEPENDENCIES = {'api': Mock(), 'services': {'profile': Mock()}} def setUp(self): self.source = SourceViewPlugin() @@ -23,5 +20,5 @@ def test_load(self): self.source.load(self.DEPENDENCIES) assert_that( calling(self.source.load).with_args(self.DEPENDENCIES), - not_(raises(Exception)) + not_(raises(Exception)), ) diff --git a/wazo_dird/plugins/profiles/http.py b/wazo_dird/plugins/profiles/http.py index fdc7e4a6..27a664b6 100644 --- a/wazo_dird/plugins/profiles/http.py +++ b/wazo_dird/plugins/profiles/http.py @@ -9,23 +9,17 @@ from wazo_dird.auth import required_acl from wazo_dird.rest_api import AuthResource -from .schemas import ( - list_schema, - profile_list_schema, - profile_schema, -) +from .schemas import list_schema, profile_list_schema, profile_schema logger = logging.getLogger(__name__) class _BaseResource(AuthResource): - def __init__(self, profile_service): self._profile_service = profile_service class Profiles(_BaseResource): - @required_acl('dird.profiles.read') def get(self): list_params, errors = list_schema.load(request.args) @@ -40,11 +34,7 @@ def get(self): filtered = self._profile_service.count(visible_tenants, **list_params) total = self._profile_service.count(visible_tenants) - return { - 'total': total, - 'filtered': filtered, - 'items': items, - } + return {'total': total, 'filtered': filtered, 'items': items} @required_acl('dird.profiles.create') def post(self): @@ -55,7 +45,6 @@ def post(self): class Profile(_BaseResource): - @required_acl('dird.profiles.{profile_uuid}.delete') def delete(self, profile_uuid): tenant_uuid = Tenant.autodetect().uuid @@ -75,5 +64,7 @@ def put(self, profile_uuid): tenant_uuid = Tenant.autodetect().uuid visible_tenants = self.get_visible_tenants(tenant_uuid) args = profile_schema.load(request.get_json()).data - self._profile_service.edit(profile_uuid, visible_tenants=visible_tenants, **args) + self._profile_service.edit( + profile_uuid, visible_tenants=visible_tenants, **args + ) return '', 204 diff --git a/wazo_dird/plugins/profiles/plugin.py b/wazo_dird/plugins/profiles/plugin.py index 14cc8d9b..0acc9632 100644 --- a/wazo_dird/plugins/profiles/plugin.py +++ b/wazo_dird/plugins/profiles/plugin.py @@ -7,15 +7,12 @@ class ProfilesViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] profile_service = dependencies['services']['profile'] api.add_resource( - http.Profiles, - '/profiles', - resource_class_args=(profile_service,), + http.Profiles, '/profiles', resource_class_args=(profile_service,) ) api.add_resource( diff --git a/wazo_dird/plugins/profiles/schemas.py b/wazo_dird/plugins/profiles/schemas.py index 29cc9182..8131d782 100644 --- a/wazo_dird/plugins/profiles/schemas.py +++ b/wazo_dird/plugins/profiles/schemas.py @@ -17,7 +17,6 @@ class ServiceConfigSchema(BaseSchema): class ServiceDictSchema(fields.Nested): - def _serialize(self, nested_obj, attr, obj, **_): if nested_obj is None: return None diff --git a/wazo_dird/plugins/reverse_service/plugin.py b/wazo_dird/plugins/reverse_service/plugin.py index 384889ab..dca62353 100644 --- a/wazo_dird/plugins/reverse_service/plugin.py +++ b/wazo_dird/plugins/reverse_service/plugin.py @@ -13,7 +13,6 @@ class ReverseServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -26,8 +25,10 @@ def load(self, dependencies): ) return self._service except KeyError: - msg = ('%s should be loaded with "config" and "source_manager" but received: %s' - % (self.__class__.__name__, ','.join(dependencies.keys()))) + msg = ( + '%s should be loaded with "config" and "source_manager" but received: %s' + % (self.__class__.__name__, ','.join(dependencies.keys())) + ) raise ValueError(msg) def unload(self): @@ -47,12 +48,16 @@ def __init__(self, *args, **kwargs): def stop(self): self._executor.shutdown() - def reverse(self, profile_config, exten, profile, args=None, xivo_user_uuid=None, token=None): + def reverse( + self, profile_config, exten, profile, args=None, xivo_user_uuid=None, token=None + ): args = args or {} futures = [] sources = self.source_from_profile(profile_config) logger.debug( - 'Reverse lookup for %s in sources %s', exten, [source.name for source in sources], + 'Reverse lookup for %s in sources %s', + exten, + [source.name for source in sources], ) for source in sources: args['token'] = token @@ -76,6 +81,8 @@ def reverse(self, profile_config, exten, profile, args=None, xivo_user_uuid=None def _async_reverse(self, source, exten, args): raise_stopper = helpers.RaiseStopper(return_on_raise=[]) - future = self._executor.submit(raise_stopper.execute, source.first_match, exten, args) + future = self._executor.submit( + raise_stopper.execute, source.first_match, exten, args + ) future.name = source.name return future diff --git a/wazo_dird/plugins/sample_backend/plugin.py b/wazo_dird/plugins/sample_backend/plugin.py index 08c691d1..1650c425 100644 --- a/wazo_dird/plugins/sample_backend/plugin.py +++ b/wazo_dird/plugins/sample_backend/plugin.py @@ -5,7 +5,9 @@ from wazo_dird import make_result_class -DESC = 'It works but this wazo-dird installation is still using the default configuration' +DESC = ( + 'It works but this wazo-dird installation is still using the default configuration' +) SAMPLE_RESULT = { 'id': 1, 'firstname': 'John', @@ -16,14 +18,15 @@ class SamplePlugin(BaseSourcePlugin): - def load(self, args): self._config = args.get('config', {}) self._name = self._config.get('name', 'sample_directory') self._format_columns = self._config.get(self.FORMAT_COLUMNS, {}) backend = self._config.get('backend', '') - SourceResult = make_result_class(backend, self._name, 'id', self._format_columns) + SourceResult = make_result_class( + backend, self._name, 'id', self._format_columns + ) self._result = SourceResult(SAMPLE_RESULT) def search(self, term, args=None): diff --git a/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py b/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py index 73afbf77..d59e2adc 100644 --- a/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py +++ b/wazo_dird/plugins/sample_backend/tests/test_sample_backend.py @@ -10,11 +10,12 @@ from ..plugin import SamplePlugin -MSG = 'It works but this wazo-dird installation is still using the default configuration' +MSG = ( + 'It works but this wazo-dird installation is still using the default configuration' +) class TestSampleBackend(unittest.TestCase): - def setUp(self): self.source = SamplePlugin() @@ -23,13 +24,15 @@ def test_load_empty_config_does_not_raise(self): def test_search(self): SourceResult = make_result_class('sample_backend', 'sample_directory', 'id') - only_result = SourceResult({ - 'id': 1, - 'firstname': 'John', - 'lastname': 'Doe', - 'number': '555', - 'description': MSG, - }) + only_result = SourceResult( + { + 'id': 1, + 'firstname': 'John', + 'lastname': 'Doe', + 'number': '555', + 'description': MSG, + } + ) self.source.load({}) results = self.source.search('anything') @@ -38,13 +41,15 @@ def test_search(self): def test_first_match(self): SourceResult = make_result_class('sample_backend', 'sample_directory', 'id') - only_result = SourceResult({ - 'id': 1, - 'firstname': 'John', - 'lastname': 'Doe', - 'number': '555', - 'description': MSG, - }) + only_result = SourceResult( + { + 'id': 1, + 'firstname': 'John', + 'lastname': 'Doe', + 'number': '555', + 'description': MSG, + } + ) self.source.load({}) result = self.source.first_match('555') diff --git a/wazo_dird/plugins/service_discovery_service/plugin.py b/wazo_dird/plugins/service_discovery_service/plugin.py index a5aad204..7e73a68a 100644 --- a/wazo_dird/plugins/service_discovery_service/plugin.py +++ b/wazo_dird/plugins/service_discovery_service/plugin.py @@ -19,7 +19,6 @@ class ServiceDiscoveryServicePlugin(BaseServicePlugin): - def __init__(self): self._service = None @@ -34,9 +33,11 @@ def load(self, dependencies): class _Service: - QUEUE = kombu.Queue(exchange=kombu.Exchange('xivo', type='topic'), - routing_key='service.registered.*', - exclusive=True) + QUEUE = kombu.Queue( + exchange=kombu.Exchange('xivo', type='topic'), + routing_key='service.registered.*', + exclusive=True, + ) def __init__(self, config, bus, source_manager, controller): self._controller = controller @@ -51,8 +52,9 @@ def __init__(self, config, bus, source_manager, controller): bus.add_consumer(self.QUEUE, self._on_service_registered) finder = ServiceFinder(config['consul']) - fetcher_thread = threading.Thread(target=self._add_remote_services, - args=(finder, service_disco_config)) + fetcher_thread = threading.Thread( + target=self._add_remote_services, args=(finder, service_disco_config) + ) fetcher_thread.daemon = True fetcher_thread.start() @@ -77,7 +79,8 @@ def _add_remote_services(self, finder, service_disco_config): def _on_service_added(self, service_name, host, port, uuid): logger.debug('%s registered %s:%s with uuid %s', service_name, host, port, uuid) config = self._source_config_generator.generate_from_new_service( - service_name, uuid, host, port) + service_name, uuid, host, port + ) if not config: return @@ -106,10 +109,12 @@ def _on_service_registered(self, body, message): else: uuid = _find_first_uuid(event.tags) if uuid: - self._on_service_added(event.service_name, - event.advertise_address, - event.advertise_port, - uuid) + self._on_service_added( + event.service_name, + event.advertise_address, + event.advertise_port, + uuid, + ) message.ack() @@ -122,7 +127,6 @@ def _find_first_uuid(tags): class ProfileConfigUpdater: - def __init__(self, config): self._config = config self._watched_services = {} @@ -167,7 +171,9 @@ def __init__(self, service_discovery_config): logger.debug('Starting with %s', service_discovery_config) template_path = service_discovery_config.get('template_path') if not template_path: - logger.info('service discovery service error: no "template_path" configured') + logger.info( + 'service discovery service error: no "template_path" configured' + ) return loader = FileSystemLoader(template_path) @@ -175,8 +181,7 @@ def __init__(self, service_discovery_config): self._host_configs = service_discovery_config['hosts'] self._template_files = { service: config['template'] - for service, config - in service_discovery_config['services'].items() + for service, config in service_discovery_config['services'].items() } self.enabled = True diff --git a/wazo_dird/plugins/service_discovery_service/tests/test_service_discovery_service.py b/wazo_dird/plugins/service_discovery_service/tests/test_service_discovery_service.py index 457d1630..e525b2ad 100644 --- a/wazo_dird/plugins/service_discovery_service/tests/test_service_discovery_service.py +++ b/wazo_dird/plugins/service_discovery_service/tests/test_service_discovery_service.py @@ -5,16 +5,10 @@ import tempfile import unittest -from hamcrest import ( - assert_that, - equal_to, -) +from hamcrest import assert_that, equal_to from mock import sentinel as s -from ..plugin import ( - ProfileConfigUpdater, - SourceConfigGenerator, -) +from ..plugin import ProfileConfigUpdater, SourceConfigGenerator TEMPLATE = '''\ @@ -57,11 +51,7 @@ 'services': { 'wazo-confd': { 'template': None, - 'lookup': { - 'foobar': True, - 'default': True, - '__switchboard': False, - }, + 'lookup': {'foobar': True, 'default': True, '__switchboard': False}, 'reverse': { 'foobar': True, 'default': False, @@ -72,17 +62,17 @@ 'default': True, '__switboard': False, }, - }, + } }, 'hosts': { 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb': { 'uuid': 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb', 'service_id': 'some-service-name', 'service_key': 'secre7', - }, + } }, }, - }, + } } @@ -91,7 +81,6 @@ class TestServiceDiscoveryServicePlugin(unittest.TestCase): class TestServiceDiscoveryService(unittest.TestCase): - def test_that_the_service_looks_for_remote_servers_when_starting(self): pass @@ -107,11 +96,12 @@ def new_template_file(content): # TODO fix when the config will be generated by events @unittest.skip class TestSourceConfigGenerator(unittest.TestCase): - def setUp(self): - (self.template_file, - self.template_dir, - self.template_filename) = new_template_file(TEMPLATE) + ( + self.template_file, + self.template_dir, + self.template_filename, + ) = new_template_file(TEMPLATE) def tearDown(self): try: @@ -128,42 +118,34 @@ def test_generate_with_an_unknown_service(self): 'uuid': 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb', 'service_id': 'some-service-name', 'service_key': 'secre7', - }, + } }, } generator = SourceConfigGenerator(service_discovery_config) - config = generator.generate_from_new_service('unknown', - s.uuid, - s.host, - s.port) + config = generator.generate_from_new_service('unknown', s.uuid, s.host, s.port) assert_that(config, equal_to(None)) def test_generate_with_an_unknown_source(self): service_discovery_config = { 'template_path': None, - 'services': { - 'wazo-confd': { - 'template': self.template_filename, - }, - }, + 'services': {'wazo-confd': {'template': self.template_filename}}, 'hosts': { 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb': { 'uuid': 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb', 'service_id': 'some-service-name', 'service_key': 'secre7', - }, + } }, } generator = SourceConfigGenerator(service_discovery_config) - config = generator.generate_from_new_service('wazo-confd', - 'other-uuid', - s.host, - s.port) + config = generator.generate_from_new_service( + 'wazo-confd', 'other-uuid', s.host, s.port + ) assert_that(config, equal_to(None)) @@ -171,40 +153,28 @@ def test_generate_with_a_service(self): uuid = 'ff791b0e-3d28-4b4d-bb90-2724c0a248cb' service_discovery_config = { 'template_path': self.template_dir, - 'services': { - 'wazo-confd': { - 'template': self.template_filename, - }, - }, + 'services': {'wazo-confd': {'template': self.template_filename}}, 'hosts': { uuid: { 'uuid': uuid, 'service_id': 'some-service-name', 'service_key': 'secre7', - }, + } }, } generator = SourceConfigGenerator(service_discovery_config) - config = generator.generate_from_new_service('wazo-confd', - uuid, - 'the-host-name', - 4567) + config = generator.generate_from_new_service( + 'wazo-confd', uuid, 'the-host-name', 4567 + ) expected = { 'type': 'wazo', 'name': 'wazo-ff791b0e-3d28-4b4d-bb90-2724c0a248cb', 'searched_columns': ['firstname', 'lastname'], 'first_matched_columns': ['exten'], - 'auth': { - 'host': 'the-host-name', - 'port': 9497, - }, - 'confd': { - 'host': 'the-host-name', - 'port': 4567, - 'version': '1.1', - }, + 'auth': {'host': 'the-host-name', 'port': 9497}, + 'confd': {'host': 'the-host-name', 'port': 4567, 'version': '1.1'}, 'format_columns': { 'number': "{exten}", 'reverse': "{firstname} {lastname}", @@ -218,7 +188,6 @@ def test_generate_with_a_service(self): # TODO fix when the config will be generated by events @unittest.skip class TestProfileConfigUpdater(unittest.TestCase): - def setUp(self): self.config = dict(CONFIG) self.source_name = 'wazo-ff791b0e-3d28-4b4d-bb90-2724c0a248cb' @@ -229,22 +198,32 @@ def test_that_on_service_added_modifies_the_config(self): updater.on_service_added(self.source_name, 'wazo-confd') expected_lookup_service = { - 'foobar': {'sources': {'source_1': True, 'source_2': True, self.source_name: True}}, - 'default': {'sources': {'source_2': True, self.source_name: True}}} + 'foobar': { + 'sources': {'source_1': True, 'source_2': True, self.source_name: True} + }, + 'default': {'sources': {'source_2': True, self.source_name: True}}, + } expected_reverse_service = { - 'foobar': {'sources': {'source_1': True, 'source_2': True, self.source_name: True}}, + 'foobar': { + 'sources': {'source_1': True, 'source_2': True, self.source_name: True} + }, 'default': {'sources': {'source_2': True}}, - '__switchboard': {'sources': {self.source_name: True}}} + '__switchboard': {'sources': {self.source_name: True}}, + } expected_favorites_service = { 'foobar': {'sources': {'source_2': True, self.source_name: True}}, - 'default': {'sources': {'source_2': True, self.source_name: True}}} - - assert_that(self.config['services']['lookup'], - equal_to(expected_lookup_service)) - assert_that(self.config['services']['reverse'], - equal_to(expected_reverse_service)) - assert_that(self.config['services']['favorites'], - equal_to(expected_favorites_service)) + 'default': {'sources': {'source_2': True, self.source_name: True}}, + } + + assert_that( + self.config['services']['lookup'], equal_to(expected_lookup_service) + ) + assert_that( + self.config['services']['reverse'], equal_to(expected_reverse_service) + ) + assert_that( + self.config['services']['favorites'], equal_to(expected_favorites_service) + ) def test_that_an_unconfigured_consul_service_does_nothing(self): original_services = dict(self.config['services']) diff --git a/wazo_dird/plugins/source_result.py b/wazo_dird/plugins/source_result.py index 3dd94c86..74eff8a1 100644 --- a/wazo_dird/plugins/source_result.py +++ b/wazo_dird/plugins/source_result.py @@ -8,14 +8,15 @@ class _NoErrorFormatter(string.Formatter): - def format(self, format_string, *args, **kwargs): try: return super().format(format_string, *args, **kwargs).strip() except Exception as e: logger.debug( 'skipping string formatting %s %s: %s', - format_string, e.__class__.__name__, e, + format_string, + e.__class__.__name__, + e, ) return None @@ -37,18 +38,25 @@ class _SourceResult: _format_columns = {} def __init__( - self, fields, xivo_id=None, agent_id=None, - user_id=None, user_uuid=None, endpoint_id=None, + self, + fields, + xivo_id=None, + agent_id=None, + user_id=None, + user_uuid=None, + endpoint_id=None, ): self._formatter = _NoErrorFormatter() self.fields = dict(fields) source_entry_id = self.get_unique() if self._unique_column else None - self.relations = {'xivo_id': xivo_id, - 'agent_id': agent_id, - 'user_id': user_id, - 'user_uuid': user_uuid, - 'endpoint_id': endpoint_id, - 'source_entry_id': source_entry_id} + self.relations = { + 'xivo_id': xivo_id, + 'agent_id': agent_id, + 'user_id': user_id, + 'user_uuid': user_uuid, + 'endpoint_id': endpoint_id, + 'source_entry_id': source_entry_id, + } self._add_formatted_columns() @@ -71,26 +79,34 @@ def _add_formatted_columns(self): self.fields[column] = value def __eq__(self, other): - return (self.source == other.source and - self.fields == other.fields and - self.relations == other.relations) + return ( + self.source == other.source + and self.fields == other.fields + and self.relations == other.relations + ) def __ne__(self, other): return not self == other def __repr__(self): - return '%s(%s, %s, %s, %s, %s, %s)' % (self.__class__.__name__, - self.fields, - self.relations['xivo_id'], - self.relations['agent_id'], - self.relations['user_id'], - self.relations['user_uuid'], - self.relations['endpoint_id']) + return '%s(%s, %s, %s, %s, %s, %s)' % ( + self.__class__.__name__, + self.fields, + self.relations['xivo_id'], + self.relations['agent_id'], + self.relations['user_id'], + self.relations['user_uuid'], + self.relations['endpoint_id'], + ) def make_result_class( - source_backend, source_name, - unique_column=None, format_columns=None, is_deletable=False, is_personal=False, + source_backend, + source_name, + unique_column=None, + format_columns=None, + is_deletable=False, + is_personal=False, ): if not unique_column: unique_column = _SourceResult._unique_column diff --git a/wazo_dird/plugins/source_service/plugin.py b/wazo_dird/plugins/source_service/plugin.py index 448bd8fe..0fa267ab 100644 --- a/wazo_dird/plugins/source_service/plugin.py +++ b/wazo_dird/plugins/source_service/plugin.py @@ -5,23 +5,18 @@ from wazo_dird.database.helpers import Session -from wazo_dird import ( - BaseServicePlugin, - database, -) +from wazo_dird import BaseServicePlugin, database logger = logging.getLogger(__name__) class SourceServicePlugin(BaseServicePlugin): - def load(self, dependencies): source_manager = dependencies['source_manager'] return _SourceService(database.SourceCRUD(Session), source_manager) class _SourceService: - def __init__(self, crud, source_manager): self._source_crud = crud self._source_manager = source_manager diff --git a/wazo_dird/plugins/sources/http.py b/wazo_dird/plugins/sources/http.py index a6818f42..b1e8cc7b 100644 --- a/wazo_dird/plugins/sources/http.py +++ b/wazo_dird/plugins/sources/http.py @@ -7,14 +7,10 @@ from wazo_dird.auth import required_acl from wazo_dird.rest_api import AuthResource -from .schemas import ( - source_list_schema, - list_schema, -) +from .schemas import source_list_schema, list_schema class Sources(AuthResource): - def __init__(self, source_service): self._source_service = source_service @@ -33,8 +29,4 @@ def get(self): filtered = self._source_service.count(backend, visible_tenants, **list_params) total = self._source_service.count(None, visible_tenants) - return { - 'total': total, - 'filtered': filtered, - 'items': items, - } + return {'total': total, 'filtered': filtered, 'items': items} diff --git a/wazo_dird/plugins/sources/plugin.py b/wazo_dird/plugins/sources/plugin.py index 8466afb1..7f9640ed 100644 --- a/wazo_dird/plugins/sources/plugin.py +++ b/wazo_dird/plugins/sources/plugin.py @@ -7,13 +7,10 @@ class SourcesViewPlugin(BaseViewPlugin): - def load(self, dependencies): api = dependencies['api'] source_service = dependencies['services']['source'] api.add_resource( - http.Sources, - '/sources', - resource_class_args=(source_service,), + http.Sources, '/sources', resource_class_args=(source_service,) ) diff --git a/wazo_dird/plugins/status/http.py b/wazo_dird/plugins/status/http.py index 8115ad1d..7174383a 100644 --- a/wazo_dird/plugins/status/http.py +++ b/wazo_dird/plugins/status/http.py @@ -6,7 +6,6 @@ class StatusResource(AuthResource): - def __init__(self, status_aggregator): self.status_aggregator = status_aggregator diff --git a/wazo_dird/plugins/status/plugin.py b/wazo_dird/plugins/status/plugin.py index f0c8c0a4..f5108ce6 100644 --- a/wazo_dird/plugins/status/plugin.py +++ b/wazo_dird/plugins/status/plugin.py @@ -15,4 +15,6 @@ def load(self, dependencies): status_aggregator = dependencies['status_aggregator'] - api.add_resource(StatusResource, '/status', resource_class_args=[status_aggregator]) + api.add_resource( + StatusResource, '/status', resource_class_args=[status_aggregator] + ) diff --git a/wazo_dird/plugins/tests/base_http_view_test_case.py b/wazo_dird/plugins/tests/base_http_view_test_case.py index 39d0ab22..a9653a46 100644 --- a/wazo_dird/plugins/tests/base_http_view_test_case.py +++ b/wazo_dird/plugins/tests/base_http_view_test_case.py @@ -7,7 +7,6 @@ class BaseHTTPViewTestCase(unittest.TestCase): - def is_route_of_app(self, http_app): return is_in(self._list_routes(http_app)) diff --git a/wazo_dird/plugins/tests/test_source_result.py b/wazo_dird/plugins/tests/test_source_result.py index e6e41847..637b96dd 100644 --- a/wazo_dird/plugins/tests/test_source_result.py +++ b/wazo_dird/plugins/tests/test_source_result.py @@ -3,13 +3,7 @@ import unittest -from hamcrest import ( - assert_that, - equal_to, - has_entries, - is_, - none, -) +from hamcrest import assert_that, equal_to, has_entries, is_, none from mock import sentinel from wazo_dird.plugins.source_result import ( _NoErrorFormatter as Formatter, @@ -19,7 +13,6 @@ class TestSourceResult(unittest.TestCase): - def setUp(self): self.xivo_id = sentinel.xivo_id self.fields = { @@ -52,33 +45,60 @@ def test_fields(self): def test_agent_relation(self): r = _SourceResult(self.fields, self.xivo_id, agent_id=sentinel.agent_id) - assert_that(r.relations, equal_to({'xivo_id': sentinel.xivo_id, - 'agent_id': sentinel.agent_id, - 'user_id': None, - 'user_uuid': None, - 'endpoint_id': None, - 'source_entry_id': None})) + assert_that( + r.relations, + equal_to( + { + 'xivo_id': sentinel.xivo_id, + 'agent_id': sentinel.agent_id, + 'user_id': None, + 'user_uuid': None, + 'endpoint_id': None, + 'source_entry_id': None, + } + ), + ) def test_user_relation(self): - r = _SourceResult(self.fields, sentinel.xivo_id, - user_id=sentinel.user_id, user_uuid=sentinel.user_uuid) + r = _SourceResult( + self.fields, + sentinel.xivo_id, + user_id=sentinel.user_id, + user_uuid=sentinel.user_uuid, + ) - assert_that(r.relations, equal_to({'xivo_id': sentinel.xivo_id, - 'agent_id': None, - 'user_id': sentinel.user_id, - 'user_uuid': sentinel.user_uuid, - 'endpoint_id': None, - 'source_entry_id': None})) + assert_that( + r.relations, + equal_to( + { + 'xivo_id': sentinel.xivo_id, + 'agent_id': None, + 'user_id': sentinel.user_id, + 'user_uuid': sentinel.user_uuid, + 'endpoint_id': None, + 'source_entry_id': None, + } + ), + ) def test_endpoint_relation(self): - r = _SourceResult(self.fields, sentinel.xivo_id, endpoint_id=sentinel.endpoint_id) + r = _SourceResult( + self.fields, sentinel.xivo_id, endpoint_id=sentinel.endpoint_id + ) - assert_that(r.relations, equal_to({'xivo_id': sentinel.xivo_id, - 'agent_id': None, - 'user_id': None, - 'user_uuid': None, - 'endpoint_id': sentinel.endpoint_id, - 'source_entry_id': None})) + assert_that( + r.relations, + equal_to( + { + 'xivo_id': sentinel.xivo_id, + 'agent_id': None, + 'user_id': None, + 'user_uuid': None, + 'endpoint_id': sentinel.endpoint_id, + 'source_entry_id': None, + } + ), + ) def test_get_unique(self): r = _SourceResult(self.fields) @@ -98,33 +118,33 @@ def test_that_format_columns_transformation_are_applied(self): 'complex_error': '{missing[0][field]}', 'super_complex_error': '{list[0][missing]}', 'crazy_error': '{list[1][missing]}', - } + }, ) r = SourceResult(self.fields) - assert_that(r.fields, has_entries( - fn='fn', - ln='ln', - name='fn ln', - simple_error=None, - complex_error=None, - super_complex_error=None, - crazy_error=None, - )) + assert_that( + r.fields, + has_entries( + fn='fn', + ln='ln', + name='fn ln', + simple_error=None, + complex_error=None, + super_complex_error=None, + crazy_error=None, + ), + ) def test_that_the_source_entry_id_is_added_to_relations(self): SourceResult = make_result_class('foo_backend', 'foobar', unique_column='email') - r = SourceResult({'fn': 'Foo', - 'ln': 'Bar', - 'email': 'foobar@example.com'}) + r = SourceResult({'fn': 'Foo', 'ln': 'Bar', 'email': 'foobar@example.com'}) assert_that(r.relations['source_entry_id'], equal_to('foobar@example.com')) class TestMakeResultClass(unittest.TestCase): - def test_source_name(self): SourceResult = make_result_class(sentinel.backend, sentinel.source_name) @@ -134,9 +154,7 @@ def test_source_name(self): def test_source_unique_column(self): SourceResult = make_result_class( - sentinel.backend, - sentinel.source_name, - 'the-unique-column' + sentinel.backend, sentinel.source_name, 'the-unique-column' ) s = SourceResult({}) @@ -146,9 +164,7 @@ def test_source_unique_column(self): def test_format_columns(self): SourceResult = make_result_class( - sentinel.backend, - sentinel.source_name, - format_columns={'to': '{from}'} + sentinel.backend, sentinel.source_name, format_columns={'to': '{from}'} ) s = SourceResult({}) @@ -158,9 +174,7 @@ def test_format_columns(self): def test_deletable(self): SourceResult = make_result_class( - sentinel.backend, - sentinel.source_name, - is_deletable=True + sentinel.backend, sentinel.source_name, is_deletable=True ) s = SourceResult({}) @@ -169,7 +183,6 @@ def test_deletable(self): class TestFormatter(unittest.TestCase): - def setUp(self): self.formatter = Formatter() @@ -179,7 +192,9 @@ def test_that_missing_keys_do_not_raise_an_exception(self): assert_that(result, equal_to('')) def test_that_a_missing_key_in_a_string_combining_two_fields(self): - result = self.formatter.format('{firstname} {lastname}', **{'firstname': 'Alice'}) + result = self.formatter.format( + '{firstname} {lastname}', **{'firstname': 'Alice'} + ) assert_that(result, equal_to('Alice')) diff --git a/wazo_dird/plugins/wazo_user_backend/contact.py b/wazo_dird/plugins/wazo_user_backend/contact.py index be0734a1..23e1a2f9 100644 --- a/wazo_dird/plugins/wazo_user_backend/contact.py +++ b/wazo_dird/plugins/wazo_user_backend/contact.py @@ -5,7 +5,6 @@ class ContactLister: - def __init__(self, client): self._client = client diff --git a/wazo_dird/plugins/wazo_user_backend/http.py b/wazo_dird/plugins/wazo_user_backend/http.py index d3f0efeb..386b4d9f 100644 --- a/wazo_dird/plugins/wazo_user_backend/http.py +++ b/wazo_dird/plugins/wazo_user_backend/http.py @@ -6,10 +6,7 @@ from xivo.tenant_flask_helpers import Tenant from wazo_dird.auth import required_acl -from wazo_dird.helpers import ( - SourceItem, - SourceList, -) +from wazo_dird.helpers import SourceItem, SourceList from wazo_dird.rest_api import AuthResource from wazo_dird.plugin_helpers.confd_client_registry import registry @@ -56,7 +53,6 @@ def put(self, source_uuid): class WazoContactList(AuthResource): - def __init__(self, source_service): self._source_service = source_service diff --git a/wazo_dird/plugins/wazo_user_backend/plugin.py b/wazo_dird/plugins/wazo_user_backend/plugin.py index 8b285538..c8db69fc 100644 --- a/wazo_dird/plugins/wazo_user_backend/plugin.py +++ b/wazo_dird/plugins/wazo_user_backend/plugin.py @@ -5,10 +5,7 @@ from requests.exceptions import ConnectionError -from wazo_dird import ( - BaseSourcePlugin, - make_result_class, -) +from wazo_dird import BaseSourcePlugin, make_result_class from wazo_dird.helpers import BaseBackendView from wazo_dird.plugin_helpers.confd_client_registry import registry @@ -41,8 +38,17 @@ def unload(self): class WazoUserPlugin(BaseSourcePlugin): - _valid_keys = ['id', 'exten', 'firstname', 'lastname', 'userfield', 'email', - 'description', 'mobile_phone_number', 'voicemail_number'] + _valid_keys = [ + 'id', + 'exten', + 'firstname', + 'lastname', + 'userfield', + 'email', + 'description', + 'mobile_phone_number', + 'voicemail_number', + ] def __init__(self): self._client = None @@ -57,10 +63,7 @@ def load(self, dependencies): self._client = registry.get(config) self._SourceResult = make_result_class( - 'wazo', - self.name, - 'id', - format_columns=config.get(self.FORMAT_COLUMNS), + 'wazo', self.name, 'id', format_columns=config.get(self.FORMAT_COLUMNS) ) self._search_params.update(config.get('extra_search_params', {})) logger.info('Wazo %s successfully loaded', config['name']) @@ -139,8 +142,7 @@ def _fetch_entries(self, term=None): ) return [] - return (self._source_result_from_entry(entry, uuid) - for entry in entries) + return (self._source_result_from_entry(entry, uuid) for entry in entries) def _get_uuid(self): if self._uuid: @@ -158,9 +160,11 @@ def _fetch_users(self, term=None): return (user for user in users['items']) def _source_result_from_entry(self, entry, uuid): - return self._SourceResult({key: entry.get(key) for key in self._valid_keys}, - xivo_id=uuid, - agent_id=entry['agent_id'], - user_id=entry['id'], - user_uuid=entry['uuid'], - endpoint_id=entry['line_id']) + return self._SourceResult( + {key: entry.get(key) for key in self._valid_keys}, + xivo_id=uuid, + agent_id=entry['agent_id'], + user_id=entry['id'], + user_uuid=entry['uuid'], + endpoint_id=entry['line_id'], + ) diff --git a/wazo_dird/plugins/wazo_user_backend/tests/test_contact_list.py b/wazo_dird/plugins/wazo_user_backend/tests/test_contact_list.py index cc2099ef..79b4e7f9 100644 --- a/wazo_dird/plugins/wazo_user_backend/tests/test_contact_list.py +++ b/wazo_dird/plugins/wazo_user_backend/tests/test_contact_list.py @@ -3,17 +3,13 @@ from unittest import TestCase -from hamcrest import ( - assert_that, - equal_to, -) +from hamcrest import assert_that, equal_to from mock import Mock from ..contact import ContactLister class TestContactLister(TestCase): - def setUp(self): self.client = Mock() @@ -23,14 +19,14 @@ def test_pagination(self): result = self.lister.list(limit=2, offset=42) assert_that(result, equal_to(self.client.users.list.return_value)) - self.client.users.list.assert_called_once_with(view='directory', limit=2, offset=42) + self.client.users.list.assert_called_once_with( + view='directory', limit=2, offset=42 + ) def test_search(self): result = self.lister.list(search='foo', firstname='john') assert_that(result, equal_to(self.client.users.list.return_value)) self.client.users.list.assert_called_once_with( - view='directory', - search='foo', - firstname='john', + view='directory', search='foo', firstname='john' ) diff --git a/wazo_dird/plugins/wazo_user_backend/tests/test_schemas.py b/wazo_dird/plugins/wazo_user_backend/tests/test_schemas.py index 17c2b03a..208703ff 100644 --- a/wazo_dird/plugins/wazo_user_backend/tests/test_schemas.py +++ b/wazo_dird/plugins/wazo_user_backend/tests/test_schemas.py @@ -20,16 +20,12 @@ class TestSourceSchema(TestCase): - def setUp(self): self._name = 'my_wazo_source' self._body = {'name': self._name} def test_post_minimal_body(self): - body = dict( - auth={'username': 'foo', 'password': 'bar'}, - **self._body - ) + body = dict(auth={'username': 'foo', 'password': 'bar'}, **self._body) parsed = source_schema.load(body).data assert_that( @@ -47,22 +43,23 @@ def test_post_minimal_body(self): verify_certificate=True, ), confd=has_entries( - host='localhost', - port=9486, - https=True, - verify_certificate=True, + host='localhost', port=9486, https=True, verify_certificate=True ), - ) + ), ) def test_that_username_password_or_keyfile_is_present(self): username_password = {'username': 'foo', 'password': 'bar'} - key_file = {'key_file': '/var/lib/wazo-auth-keys/wazo-dird-wazo-backend-key.yml'} + key_file = { + 'key_file': '/var/lib/wazo-auth-keys/wazo-dird-wazo-backend-key.yml' + } username_and_key_file = {'username': 'foo', 'key_file': 'bar'} no_auth_info = {} assert_that( - calling(source_schema.load).with_args(dict(auth=username_password, **self._body)), + calling(source_schema.load).with_args( + dict(auth=username_password, **self._body) + ), not_(raises(Exception)), ) @@ -72,12 +69,16 @@ def test_that_username_password_or_keyfile_is_present(self): ) assert_that( - calling(source_schema.load).with_args(dict(auth=no_auth_info, **self._body)), + calling(source_schema.load).with_args( + dict(auth=no_auth_info, **self._body) + ), raises(ValidationError), ) assert_that( - calling(source_schema.load).with_args(dict(auth=username_and_key_file, **self._body)), + calling(source_schema.load).with_args( + dict(auth=username_and_key_file, **self._body) + ), raises(ValidationError), ) @@ -85,7 +86,10 @@ def test_verify_certificate(self): cert_filename = '/usr/share/xivo-certs/server.crt' verify_true = {'verify_certificate': True, 'key_file': '/not/important'} verify_false = {'verify_certificate': False, 'key_file': '/not/important'} - verify_file = {'verify_certificate': cert_filename, 'key_file': '/not/important'} + verify_file = { + 'verify_certificate': cert_filename, + 'key_file': '/not/important', + } body = dict(auth=verify_true, confd=verify_true, **self._body) parsed = source_schema.load(body).data @@ -94,7 +98,7 @@ def test_verify_certificate(self): has_entries( auth=has_entries(verify_certificate=True), confd=has_entries(verify_certificate=True), - ) + ), ) body = dict(auth=verify_false, confd=verify_false, **self._body) @@ -104,7 +108,7 @@ def test_verify_certificate(self): has_entries( auth=has_entries(verify_certificate=False), confd=has_entries(verify_certificate=False), - ) + ), ) body = dict(auth=verify_file, confd=verify_file, **self._body) @@ -114,5 +118,5 @@ def test_verify_certificate(self): has_entries( auth=has_entries(verify_certificate=cert_filename), confd=has_entries(verify_certificate=cert_filename), - ) + ), ) diff --git a/wazo_dird/plugins/wazo_user_backend/tests/test_wazo_user_backend.py b/wazo_dird/plugins/wazo_user_backend/tests/test_wazo_user_backend.py index ffc71244..6685cb15 100644 --- a/wazo_dird/plugins/wazo_user_backend/tests/test_wazo_user_backend.py +++ b/wazo_dird/plugins/wazo_user_backend/tests/test_wazo_user_backend.py @@ -3,18 +3,8 @@ import unittest -from hamcrest import ( - assert_that, - contains, - equal_to, - empty, - is_, - none, -) -from mock import ( - Mock, - patch, -) +from hamcrest import assert_that, contains, equal_to, empty, is_, none +from mock import Mock, patch from wazo_dird import make_result_class from ..plugin import WazoUserPlugin @@ -26,11 +16,7 @@ 'username': 'foo', 'password': 'bar', } -CONFD_CONFIG = { - 'host': 'xivo.example.com', - 'port': 9486, - 'version': '1.1', -} +CONFD_CONFIG = {'host': 'xivo.example.com', 'port': 9486, 'version': '1.1'} DEFAULT_ARGS = { 'config': { 'uuid': 'ae086548-2d36-4367-8914-8dfcd8645ca7', @@ -40,15 +26,18 @@ 'auth': AUTH_CONFIG, 'name': 'my_test_xivo', 'searched_columns': ['firstname', 'lastname'], - }, + } } UUID = 'my-xivo-uuid' UUID_1 = '55abf77c-5744-44a0-9c36-34da29f647cb' UUID_2 = '22f51ae2-296d-4340-a7d5-3567ae66df73' -SourceResult = make_result_class(DEFAULT_ARGS['config']['backend'], DEFAULT_ARGS['config']['name'], - unique_column='id') +SourceResult = make_result_class( + DEFAULT_ARGS['config']['backend'], + DEFAULT_ARGS['config']['name'], + unique_column='id', +) CONFD_USER_1 = { "agent_id": 42, @@ -61,15 +50,8 @@ 'userfield': None, 'description': None, "links": [ - { - "href": "http://localhost:9487/1.1/users/226", - "rel": "users" - }, - { - "href": "http://localhost:9487/1.1/lines/123", - "rel": "lines" - } - + {"href": "http://localhost:9487/1.1/users/226", "rel": "users"}, + {"href": "http://localhost:9487/1.1/lines/123", "rel": "lines"}, ], "email": "louis-jean@aucun.com", "mobile_phone_number": "5555551234", @@ -77,15 +59,17 @@ } SOURCE_1 = SourceResult( - {'id': 226, - 'exten': '666', - 'firstname': 'Louis-Jean', - 'lastname': '', - 'userfield': None, - 'description': None, - 'email': 'louis-jean@aucun.com', - 'mobile_phone_number': '5555551234', - 'voicemail_number': '1234'}, + { + 'id': 226, + 'exten': '666', + 'firstname': 'Louis-Jean', + 'lastname': '', + 'userfield': None, + 'description': None, + 'email': 'louis-jean@aucun.com', + 'mobile_phone_number': '5555551234', + 'voicemail_number': '1234', + }, xivo_id=UUID, agent_id=42, user_id=226, @@ -104,14 +88,8 @@ 'userfield': '555', 'description': 'here', "links": [ - { - "href": "http://localhost:9487/1.1/users/227", - "rel": "users" - }, - { - "href": "http://localhost:9487/1.1/lines/320", - "rel": "lines" - }, + {"href": "http://localhost:9487/1.1/users/227", "rel": "users"}, + {"href": "http://localhost:9487/1.1/lines/320", "rel": "lines"}, ], 'email': '', "mobile_phone_number": "", @@ -119,15 +97,17 @@ } SOURCE_2 = SourceResult( - {'id': 227, - 'exten': '1234', - 'firstname': 'Paul', - 'lastname': '', - 'email': '', - 'mobile_phone_number': '', - 'userfield': '555', - 'description': 'here', - 'voicemail_number': None}, + { + 'id': 227, + 'exten': '1234', + 'firstname': 'Paul', + 'lastname': '', + 'email': '', + 'mobile_phone_number': '', + 'userfield': '555', + 'description': 'here', + 'voicemail_number': None, + }, xivo_id=UUID, user_id=227, user_uuid=UUID_2, @@ -136,7 +116,6 @@ class _BaseTest(unittest.TestCase): - def setUp(self): self._source = WazoUserPlugin() self._confd_client = Mock() @@ -144,7 +123,6 @@ def setUp(self): class TestWazoUserBackendSearch(_BaseTest): - def setUp(self): super().setUp() response = {'items': [CONFD_USER_1, CONFD_USER_2]} @@ -159,7 +137,8 @@ def test_search_on_excluded_column(self): result = self._source.search(term='paul') self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory', search='paul') + recurse=True, view='directory', search='paul' + ) assert_that(result, empty()) @@ -169,7 +148,8 @@ def test_search_on_included_column(self): result = self._source.search(term='paul') self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory', search='paul') + recurse=True, view='directory', search='paul' + ) assert_that(result, contains(SOURCE_2)) @@ -184,10 +164,7 @@ def test_that_search_uses_extra_search_params(self): client = registry.get.return_value client.users.list.assert_called_once_with( - recurse=True, - view='directory', - search='paul', - context='inside', + recurse=True, view='directory', search='paul', context='inside' ) def test_first_match(self): @@ -196,7 +173,8 @@ def test_first_match(self): result = self._source.first_match('1234') self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory', search='1234') + recurse=True, view='directory', search='1234' + ) assert_that(result, equal_to(SOURCE_2)) @@ -206,7 +184,8 @@ def test_first_match_return_none_when_no_result(self): result = self._source.first_match('12') self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory', search='12') + recurse=True, view='directory', search='12' + ) assert_that(result, is_(none())) @@ -214,7 +193,8 @@ def test_list_with_unknown_id(self): result = self._source.list(unique_ids=['42']) self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory') + recurse=True, view='directory' + ) assert_that(result, empty()) @@ -222,7 +202,8 @@ def test_list_with_known_id(self): result = self._source.list(unique_ids=['226']) self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory') + recurse=True, view='directory' + ) assert_that(result, contains(SOURCE_1)) @@ -230,7 +211,8 @@ def test_list_with_empty_list(self): result = self._source.list(unique_ids=[]) self._confd_client.users.list.assert_called_once_with( - recurse=True, view='directory') + recurse=True, view='directory' + ) assert_that(result, contains()) diff --git a/wazo_dird/rest_api.py b/wazo_dird/rest_api.py index 18b97054..5d087a1b 100644 --- a/wazo_dird/rest_api.py +++ b/wazo_dird/rest_api.py @@ -33,7 +33,6 @@ class CoreRestApi: - def __init__(self, global_config): self.config = global_config['rest_api'] self.app = Flask('wazo_dird', template_folder=TEMPLATE_FOLDER) @@ -44,7 +43,9 @@ def __init__(self, global_config): @self.babel.localeselector def get_locale(): - translations = [str(translation) for translation in self.babel.list_translations()] + translations = [ + str(translation) for translation in self.babel.list_translations() + ] return request.accept_languages.best_match(translations) http_helpers.add_logger(self.app, logger) @@ -68,14 +69,18 @@ def run(self): bind_addr = (https_config['listen'], https_config['port']) - wsgi_app = ReverseProxied(ProxyFix(wsgi.WSGIPathInfoDispatcher({'/': self.app}))) - server = wsgi.WSGIServer(bind_addr=bind_addr, - wsgi_app=wsgi_app) - server.ssl_adapter = http_helpers.ssl_adapter(https_config['certificate'], - https_config['private_key']) + wsgi_app = ReverseProxied( + ProxyFix(wsgi.WSGIPathInfoDispatcher({'/': self.app})) + ) + server = wsgi.WSGIServer(bind_addr=bind_addr, wsgi_app=wsgi_app) + server.ssl_adapter = http_helpers.ssl_adapter( + https_config['certificate'], https_config['private_key'] + ) logger.debug( 'WSGIServer starting... uid: %s, listen: %s:%s', - os.getuid(), bind_addr[0], bind_addr[1], + os.getuid(), + bind_addr[0], + bind_addr[1], ) for route in http_helpers.list_routes(self.app): logger.debug(route) @@ -99,6 +104,7 @@ def wrapper(*args, **kwargs): } logger.error('%s: %s', error.message, error.details) return response, error.status_code + return wrapper @@ -108,7 +114,7 @@ class LegacyErrorCatchingResource(Resource): class LegacyAuthResource(LegacyErrorCatchingResource): method_decorators = [ - auth_verifier.verify_token, + auth_verifier.verify_token ] + LegacyErrorCatchingResource.method_decorators @@ -121,7 +127,9 @@ class ErrorCatchingResource(Resource): class AuthResource(ErrorCatchingResource): - method_decorators = [auth_verifier.verify_token] + ErrorCatchingResource.method_decorators + method_decorators = [ + auth_verifier.verify_token + ] + ErrorCatchingResource.method_decorators def get_visible_tenants(self, tenant): token = request.headers['X-Auth-Token'] @@ -134,7 +142,9 @@ def get_visible_tenants(self, tenant): response = getattr(e, 'response', None) status_code = getattr(response, 'status_code', None) if status_code == 401: - logger.warning('a user is doing multi-tenant queries without the tenant list ACL') + logger.warning( + 'a user is doing multi-tenant queries without the tenant list ACL' + ) return [tenant] raise diff --git a/wazo_dird/schemas.py b/wazo_dird/schemas.py index 18c204b2..9bb5f054 100644 --- a/wazo_dird/schemas.py +++ b/wazo_dird/schemas.py @@ -1,24 +1,12 @@ # Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later -from marshmallow import ( - exceptions, - Schema, - compat, - pre_load, - utils, - validates_schema, -) +from marshmallow import exceptions, Schema, compat, pre_load, utils, validates_schema from xivo.mallow import fields -from xivo.mallow.validate import ( - Length, - Range, - validate_string_dict, -) +from xivo.mallow.validate import Length, Range, validate_string_dict class BaseSchema(Schema): - class Meta: ordered = True strict = True @@ -29,7 +17,6 @@ def ensude_dict(self, data): class VerifyCertificateField(fields.Field): - def _deserialize(self, value, attr, data): if value in (True, 'true', 'True'): return True @@ -50,8 +37,12 @@ class BaseSourceSchema(BaseSchema): uuid = fields.UUID(dump_only=True) tenant_uuid = fields.UUID(dump_only=True) name = fields.String(validate=Length(min=1, max=512), required=True) - first_matched_columns = fields.List(fields.String(validate=Length(min=1, max=128)), missing=[]) - searched_columns = fields.List(fields.String(validate=Length(min=1, max=128)), missing=[]) + first_matched_columns = fields.List( + fields.String(validate=Length(min=1, max=128)), missing=[] + ) + searched_columns = fields.List( + fields.String(validate=Length(min=1, max=128)), missing=[] + ) format_columns = fields.Dict(validate=validate_string_dict, missing={}) @@ -81,12 +72,12 @@ def validate_auth_info(self, data): if key_file and username: raise exceptions.ValidationError( - 'a "key_file" or a "username" and "password" must be specified', + 'a "key_file" or a "username" and "password" must be specified' ) if key_file or username: return raise exceptions.ValidationError( - 'a "key_file" or a "username" and "password" must be specified', + 'a "key_file" or a "username" and "password" must be specified' ) diff --git a/wazo_dird/service_discovery.py b/wazo_dird/service_discovery.py index 05d599d5..4407b61a 100644 --- a/wazo_dird/service_discovery.py +++ b/wazo_dird/service_discovery.py @@ -8,7 +8,9 @@ def self_check(port): url = 'https://localhost:{}/0.1/directories/lookup/foobar/headers'.format(port) try: - response = requests.get(url, headers={'accept': 'application/json'}, verify=False) + response = requests.get( + url, headers={'accept': 'application/json'}, verify=False + ) return response.status_code == 401 except Exception: return False diff --git a/wazo_dird/source_manager.py b/wazo_dird/source_manager.py index f2490df2..6fef4aa4 100644 --- a/wazo_dird/source_manager.py +++ b/wazo_dird/source_manager.py @@ -90,6 +90,7 @@ def _add_source_with_config(self, extension, config): source.load(dependencies) self._sources[source.name] = source except Exception: - logger.exception('Failed to load back-end `%s` with config `%s`', - extension.name, name) + logger.exception( + 'Failed to load back-end `%s` with config `%s`', extension.name, name + ) return source diff --git a/wazo_dird/tests/test_config.py b/wazo_dird/tests/test_config.py index 5e1c03de..635c72ff 100644 --- a/wazo_dird/tests/test_config.py +++ b/wazo_dird/tests/test_config.py @@ -13,8 +13,9 @@ @patch('builtins.print', Mock()) @patch('wazo_dird.config.open', create=True) class TestConfig(TestCase): - - def test_load_when_no_args_and_no_default_config_file_then_default_values(self, mock_open): + def test_load_when_no_args_and_no_default_config_file_then_default_values( + self, mock_open + ): mock_open.side_effect = IOError('no such file') config._DEFAULT_CONFIG = { 'config': 'default', diff --git a/wazo_dird/tests/test_controller.py b/wazo_dird/tests/test_controller.py index 95972713..7d19b898 100644 --- a/wazo_dird/tests/test_controller.py +++ b/wazo_dird/tests/test_controller.py @@ -16,7 +16,6 @@ @patch('wazo_dird.controller.TokenRenewer', TokenRenewer) @patch('wazo_dird.controller.init_db', Mock()) class TestController(TestCase): - def setUp(self): self.rest_api = patch('wazo_dird.controller.CoreRestApi').start().return_value self.load_services = patch('wazo_dird.plugin_manager.load_services').start() @@ -27,25 +26,31 @@ def tearDown(self): patch.stopall() def test_run_starts_rest_api(self): - config = self._create_config(**{ - 'rest_api': { - 'https': {'listen': '127.0.0.1', 'port': '9489', 'certificate': 'my-certificate'}, - }, - 'debug': s.debug, - 'service_discovery': {'enabled': False}, - }) + config = self._create_config( + **{ + 'rest_api': { + 'https': { + 'listen': '127.0.0.1', + 'port': '9489', + 'certificate': 'my-certificate', + } + }, + 'debug': s.debug, + 'service_discovery': {'enabled': False}, + } + ) Controller(config).run() self.rest_api.run.assert_called_once_with() def test_run_loads_and_unloads_services(self): - config = self._create_config(**{ - 'enabled_plugins': { - 'services': s.enabled, - }, - 'services': s.config, - 'service_discovery': {'enabled': False}, - }) + config = self._create_config( + **{ + 'enabled_plugins': {'services': s.enabled}, + 'services': s.config, + 'service_discovery': {'enabled': False}, + } + ) Controller(config).run() @@ -53,23 +58,19 @@ def test_run_loads_and_unloads_services(self): self.unload_services.assert_called_once_with() def test_run_loads_views(self): - config = self._create_config(**{ - 'enabled_plugins': { - 'views': s.enabled, - }, - 'views': s.config, - 'service_discovery': {'enabled': False}, - }) + config = self._create_config( + **{ + 'enabled_plugins': {'views': s.enabled}, + 'views': s.config, + 'service_discovery': {'enabled': False}, + } + ) controller = Controller(config) controller.run() self.load_views.assert_called_once_with( - config, - s.enabled, - ANY, - controller.auth_client, - controller.status_aggregator, + config, s.enabled, ANY, controller.auth_client, controller.status_aggregator ) def _create_config(self, **kwargs): @@ -81,7 +82,9 @@ def _create_config(self, **kwargs): config['enabled_plugins'].setdefault('services', {}) config['enabled_plugins'].setdefault('views', {}) config.setdefault('sources', {}) - config.setdefault('rest_api', {'https': {'port': Mock(), 'certificate': 'my-certificate'}}) + config.setdefault( + 'rest_api', {'https': {'port': Mock(), 'certificate': 'my-certificate'}} + ) config.setdefault('services', Mock()) config.setdefault('source_config_dir', Mock()) config.setdefault('views', Mock()) diff --git a/wazo_dird/tests/test_helpers.py b/wazo_dird/tests/test_helpers.py index 3977696a..beb1b3fd 100644 --- a/wazo_dird/tests/test_helpers.py +++ b/wazo_dird/tests/test_helpers.py @@ -18,7 +18,6 @@ def _throwing(): class TestNoThrowExecute(unittest.TestCase): - def test_that_the_result_is_returned(self): result = RaiseStopper(return_on_raise=None).execute(_ok, 1, 2) diff --git a/wazo_dird/tests/test_main.py b/wazo_dird/tests/test_main.py index 08b53ab4..225587b9 100644 --- a/wazo_dird/tests/test_main.py +++ b/wazo_dird/tests/test_main.py @@ -3,15 +3,8 @@ from unittest import TestCase -from hamcrest import ( - assert_that, - equal_to, -) -from mock import ( - ANY, - patch, - sentinel as s, -) +from hamcrest import assert_that, equal_to +from mock import ANY, patch, sentinel as s from ..main import main @@ -23,7 +16,6 @@ @patch('wazo_dird.main.Controller') @patch('wazo_dird.main.load_config') class TestWazoDird(TestCase): - def test_main_injects_argv_into_config_loading(self, load_config, *_): main(s.argv) @@ -49,10 +41,7 @@ def test_main_setup_logging(self, load_config, _, xivo_logging, *__): main(s.argv) xivo_logging.setup_logging.assert_called_once_with( - s.log_filename, - s.foreground, - s.debug, - s.log_level, + s.log_filename, s.foreground, s.debug, s.log_level ) def test_main_when_config_user_then_change_user( diff --git a/wazo_dird/tests/test_plugin_manager.py b/wazo_dird/tests/test_plugin_manager.py index ca02412a..6728c8ae 100644 --- a/wazo_dird/tests/test_plugin_manager.py +++ b/wazo_dird/tests/test_plugin_manager.py @@ -3,30 +3,26 @@ from unittest import TestCase -from hamcrest import ( - assert_that, - calling, - not_, - raises, -) -from mock import ( - Mock, - patch, -) +from hamcrest import assert_that, calling, not_, raises +from mock import Mock, patch from wazo_dird import plugin_manager class TestPluginManagerServices(TestCase): - def test_unload_services_calls_unload_on_services(self): plugin_manager.services_extension_manager = Mock() plugin_manager.unload_services() - plugin_manager.services_extension_manager.map_method.assert_called_once_with('unload') + plugin_manager.services_extension_manager.map_method.assert_called_once_with( + 'unload' + ) - def test_that_unload_services_does_nothing_when_load_services_has_not_been_run(self): + def test_that_unload_services_does_nothing_when_load_services_has_not_been_run( + self + ): with patch('wazo_dird.plugin_manager.services_extension_manager', None): - assert_that(calling(plugin_manager.unload_services), - not_(raises(Exception))) + assert_that( + calling(plugin_manager.unload_services), not_(raises(Exception)) + ) diff --git a/wazo_dird/tests/test_source_manager.py b/wazo_dird/tests/test_source_manager.py index 8e90ed1a..fbe7e8d4 100644 --- a/wazo_dird/tests/test_source_manager.py +++ b/wazo_dird/tests/test_source_manager.py @@ -9,7 +9,6 @@ class TestSourceManager(unittest.TestCase): - def test_unload_sources(self): source_1 = Mock() source_2 = Mock() From 3b62090a2408b8a97c631c9a393f64d22f6ff78c Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Wed, 10 Jul 2019 13:15:26 -0400 Subject: [PATCH 18/24] tests: reuse the test-requirements-for-tox in test-requirements --- integration_tests/test-requirements.txt | 30 ++----------------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/integration_tests/test-requirements.txt b/integration_tests/test-requirements.txt index 10fc7545..a9e9adab 100644 --- a/integration_tests/test-requirements.txt +++ b/integration_tests/test-requirements.txt @@ -1,30 +1,4 @@ -https://github.com/wazo-pbx/xivo-bus/archive/master.zip -https://github.com/wazo-pbx/xivo-test-helpers/archive/master.zip -https://github.com/wazo-pbx/xivo-lib-python/archive/master.zip +# Backward compatiblity for jenkins -babel -flask-babel -docker-compose -openapi-spec-validator -pyhamcrest -# pytest 4.2.0 has a bug: https://github.com/pytest-dev/pytest/issues/4700 -pytest!=4.2.0 -python-ldap -sh -mock - -# for database tests +-r test-requirements-for-tox.txt -e .. -psycopg2-binary -sqlalchemy==1.0.15 -unidecode==0.04.19 -cheroot==6.5.2 -kombu -stevedore -flask-restful==0.3.5 -flask-cors==3.0.2 -marshmallow==2.16.3 -https://github.com/wazo-pbx/wazo-auth-client/archive/master.zip -https://github.com/wazo-pbx/wazo-confd-client/archive/master.zip -https://github.com/wazo-pbx/xivo-lib-rest-client/archive/master.zip -https://github.com/wazo-pbx/wazo-dird-client/archive/master.zip From 3100399a45a21a443696cc8c107bcc043eabbece Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Wed, 10 Jul 2019 13:24:07 -0400 Subject: [PATCH 19/24] tox: enable tox during -elinters --- tox.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 241fe552..8ffe3f66 100644 --- a/tox.ini +++ b/tox.ini @@ -51,8 +51,7 @@ deps = flake8 flake8-colors black commands = - # do not fail for black - -black --skip-string-normalization --check . + black --skip-string-normalization --check . flake8 [testenv:integration] From 028849b164c5135e98bfe7d74380976d5697ad99 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Thu, 18 Jul 2019 08:45:38 -0400 Subject: [PATCH 20/24] integration tests: add a bindep.txt for the test VM --- bindep.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 bindep.txt diff --git a/bindep.txt b/bindep.txt new file mode 100644 index 00000000..edf125d2 --- /dev/null +++ b/bindep.txt @@ -0,0 +1,3 @@ +libldap2-dev [platform:dpkg] +libsasl2-dev [platform:dpkg] +libssl-dev [platform:dpkg] From 90cd813a668e76fc792f8f5531f8de50b253caaa Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Thu, 18 Jul 2019 10:24:34 -0400 Subject: [PATCH 21/24] zuul: allow the integration tests to run for 3 hours --- zuul.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/zuul.yaml b/zuul.yaml index 1bb29906..c9aac9d2 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -2,4 +2,9 @@ templates: - wazo-tox-linters - wazo-tox-py35 - - wazo-tox-integration + +- job: + name: dird-tox-integration + description: Run dird integration tests + parent: wazo-tox-integration + timeout: 10800 From 7fec05dd3a46939717bd3b20551f0084fcae081e Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Thu, 18 Jul 2019 10:43:20 -0400 Subject: [PATCH 22/24] zuul: add the dird-tox-integration job to the project check and gate --- zuul.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/zuul.yaml b/zuul.yaml index c9aac9d2..56603b4d 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -2,6 +2,14 @@ templates: - wazo-tox-linters - wazo-tox-py35 + check: + jobs: + - dird-tox-integration: + nodeset: debian9-vm + gate: + jobs: + - dird-tox-integration: + nodeset: debian9-vm - job: name: dird-tox-integration From 2ff97b1b7579e4e00f88de1e46f4483d50404b79 Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Thu, 18 Jul 2019 14:00:48 -0400 Subject: [PATCH 23/24] zuul/tox: try to add the INTEGRATION_TEST_TIMEOUT env variable --- tox.ini | 1 + zuul.yaml | 2 ++ 2 files changed, 3 insertions(+) diff --git a/tox.ini b/tox.ini index 8ffe3f66..7a14fd92 100644 --- a/tox.ini +++ b/tox.ini @@ -60,6 +60,7 @@ deps = -rintegration_tests/test-requirements-for-tox.txt changedir = integration_tests passenv = WAZO_TEST_DOCKER_OVERRIDE_EXTRA + INTEGRATION_TEST_TIMEOUT commands = make test-setup pytest {posargs} diff --git a/zuul.yaml b/zuul.yaml index 56603b4d..9bb184af 100644 --- a/zuul.yaml +++ b/zuul.yaml @@ -16,3 +16,5 @@ description: Run dird integration tests parent: wazo-tox-integration timeout: 10800 + vars: + integration_test_timeout: 60 From 971cececfb8e06d4dcea724039ee108e3a6a69ac Mon Sep 17 00:00:00 2001 From: Pascal Cadotte Michaud Date: Thu, 18 Jul 2019 15:13:07 -0400 Subject: [PATCH 24/24] tests: pull images before building new images --- integration_tests/Makefile | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/integration_tests/Makefile b/integration_tests/Makefile index 59e317ce..9be23707 100644 --- a/integration_tests/Makefile +++ b/integration_tests/Makefile @@ -1,9 +1,11 @@ -.PHONY: test-setup build-dird build-db-image egg-info test microsoft-mock +.PHONY: test-setup build-dird build-db-image egg-info test microsoft-mock pull-images microsoft-mock: docker build --no-cache -t microsoft-mock -f assets/microsoft-mock/Dockerfile assets/microsoft-mock -test-setup: egg-info build-dird build-db-image microsoft-mock +test-setup: egg-info pull-images build-dird build-db-image microsoft-mock + +pull-images: docker pull alpine docker pull nickstenning/slapd docker pull p0bailey/docker-flask @@ -13,6 +15,7 @@ test-setup: egg-info build-dird build-db-image microsoft-mock docker pull wazopbx/wait docker pull wazopbx/wazo-auth-mock + build-dird: docker build -t wazopbx/wazo-dird .. docker build --no-cache -t wazo-dird-test -f docker/Dockerfile-dird-test ..