Skip to content

Commit

Permalink
DESENG-481: Adding unit tests for met api (#2360)
Browse files Browse the repository at this point in the history
* Adding unit tests for met api
  • Loading branch information
VineetBala-AOT authored Jan 23, 2024
1 parent 027366f commit 49819b6
Show file tree
Hide file tree
Showing 31 changed files with 2,550 additions and 127 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.MD
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## January 22, 2024
- **Task** Add missing unit tests for met api [🎟️DESENG-481](https://apps.itsm.gov.bc.ca/jira/browse/DESENG-481)
- Added missing unit tests for met api
- Added unit tests for error handling for met api

## January 15, 2024

- **Task** Audit for missing unit tests [🎟️DESENG-436](https://apps.itsm.gov.bc.ca/jira/browse/DESENG-436)
Expand Down
5 changes: 3 additions & 2 deletions met-api/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ JWT_OIDC_ISSUER="" # default: constructed from base url and realm name
JWT_OIDC_WELL_KNOWN_CONFIG="" # default: constructed from issuer
JWT_OIDC_JWKS_URI="" # default: constructed from issuer
# Object path to access roles from JWT token
JWT_OIDC_ROLE_CLAIM=realm_access.roles # SSO schema
# JWT_OIDC_ROLE_CLAIM=client_roles # Keycloak schema
# JWT_OIDC_ROLE_CLAIM=realm_access.roles # SSO schema
JWT_OIDC_ROLE_CLAIM=client_roles # Keycloak schema
JWT_OIDC_CACHING_ENABLED=true # Enable caching of JWKS.
JWT_OIDC_JWKS_CACHE_TIMEOUT=300 # Timeout for JWKS cache in seconds.

Expand Down Expand Up @@ -124,6 +124,7 @@ DATABASE_TEST_NAME=
DATABASE_TEST_HOST=
DATABASE_TEST_PORT=

# A keycloak server is started automatically by Pytest; there is no need to start your own instance.
KEYCLOAK_TEST_BASE_URL="http://localhost:8081"

# Docker database settings
Expand Down
2 changes: 1 addition & 1 deletion met-api/src/met_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def SQLALCHEMY_DATABASE_URI(self) -> str:
'AUDIENCE': os.getenv('JWT_OIDC_AUDIENCE', 'account'),
'CACHING_ENABLED': str(env_truthy('JWT_OIDC_CACHING_ENABLED', 'True')),
'JWKS_CACHE_TIMEOUT': int(os.getenv('JWT_OIDC_JWKS_CACHE_TIMEOUT', '300')),
'ROLE_CLAIM': os.getenv('JWT_OIDC_ROLE_CLAIM', 'realm_access.roles'),
'ROLE_CLAIM': os.getenv('JWT_OIDC_ROLE_CLAIM', 'client_roles'),
}

# PostgreSQL configuration
Expand Down
1 change: 1 addition & 0 deletions met-api/src/met_api/constants/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ class WidgetType(IntEnum):
EVENTS = 5
Map = 6
Video = 7
Timeline = 9
2 changes: 1 addition & 1 deletion met-api/src/met_api/models/widget_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def get_map(cls, widget_id) -> list[WidgetMap]:
@classmethod
def update_map(cls, widget_id, map_data: dict) -> WidgetMap:
"""Update map."""
query = WidgetMap.query.filter_by(WidgetMap.widget_id == widget_id)
query = WidgetMap.query.filter_by(widget_id=widget_id)
widget_map: WidgetMap = query.first()
if not widget_map:
return map_data
Expand Down
3 changes: 2 additions & 1 deletion met-api/src/met_api/services/engagement_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ def get_engagement(self, engagement_id) -> EngagementSchema:

engagement = EngagementSchema().dump(engagement_model)
engagement['banner_url'] = self.object_storage.get_url(engagement['banner_filename'])
return engagement
return engagement
return None

def get_engagements_paginated(
self,
Expand Down
156 changes: 156 additions & 0 deletions met-api/tests/unit/api/test_cac_form.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests to verify the CAC Form API end-point.
Test-Suite to ensure that the /cacform endpoint is working as expected.
"""
import json
from http import HTTPStatus
from unittest.mock import MagicMock, patch
import pytest

from met_api.exceptions.business_exception import BusinessException
from met_api.services.cac_form_service import CACFormService
from met_api.utils.enums import ContentType
from tests.utilities.factory_scenarios import TestCACForm, TestJwtClaims, TestSubscribeInfo, TestWidgetInfo
from tests.utilities.factory_utils import factory_auth_header, factory_engagement_model, factory_widget_model


def create_widget_subscription(client, jwt, widget_id, headers):
"""Add subscribe widget to the engagement."""
data = {
**TestSubscribeInfo.subscribe_info_2.value,
'widget_id': widget_id,
}
return client.post(
f'/api/widgets/{widget_id}/subscribe',
data=json.dumps(data),
headers=headers,
content_type=ContentType.JSON.value,
)


def create_cac_form_submission(client, jwt, engagement_id, widget_id, form_data, headers):
"""Create CAC Form data."""
return client.post(
f'/api/engagements/{engagement_id}/cacform/{widget_id}',
data=json.dumps(form_data),
headers=headers,
content_type=ContentType.JSON.value,
)


@pytest.mark.parametrize('side_effect, expected_status', [
(KeyError('Test error'), HTTPStatus.BAD_REQUEST),
(ValueError('Test error'), HTTPStatus.BAD_REQUEST),
])
def test_create_form_submission(client, jwt, session, side_effect,
expected_status): # pylint:disable=unused-argument
"""Assert that cac form submission can be POSTed."""
engagement = factory_engagement_model()
TestWidgetInfo.widget_subscribe['engagement_id'] = engagement.id
widget = factory_widget_model(TestWidgetInfo.widget_subscribe)
form_data = TestCACForm.form_data.value

headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.no_role)

rv = create_widget_subscription(client, jwt, widget.id, headers)
# Checking response
assert rv.status_code == HTTPStatus.OK.value

# Sending POST request for CAC
rv = create_cac_form_submission(client, jwt, engagement.id, widget.id, form_data, headers)
# Checking response
assert rv.status_code == HTTPStatus.OK.value
response_data = json.loads(rv.data)
assert response_data.get('engagement_id') == engagement.id

with patch.object(CACFormService, 'create_form_submission', side_effect=side_effect):
rv = client.post(
f'/api/engagements/{engagement.id}/cacform/{widget.id}',
data=json.dumps(form_data),
headers=headers,
content_type=ContentType.JSON.value,
)
assert rv.status_code == expected_status

with patch.object(CACFormService, 'create_form_submission',
side_effect=BusinessException('Test error', status_code=HTTPStatus.BAD_REQUEST)):
rv = client.post(
f'/api/engagements/{engagement.id}/cacform/{widget.id}',
data=json.dumps(form_data),
headers=headers,
content_type=ContentType.JSON.value,
)
assert rv.status_code == HTTPStatus.BAD_REQUEST


@pytest.mark.parametrize('side_effect, expected_status', [
(KeyError('Test error'), HTTPStatus.INTERNAL_SERVER_ERROR),
(ValueError('Test error'), HTTPStatus.INTERNAL_SERVER_ERROR),
])
def test_get_cac_form_spreadsheet(mocker, client, jwt, session, side_effect, expected_status,
setup_admin_user_and_claims): # pylint:disable=unused-argument
"""Assert that cac form submissions sheet can be fetched."""
user, claims = setup_admin_user_and_claims
mock_post_generate_document_response = MagicMock()
mock_post_generate_document_response.content = b'mock data'
mock_post_generate_document_response.headers = {}
mock_post_generate_document_response.status_code = 200
mock_post_generate_document = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._post_generate_document',
return_value=mock_post_generate_document_response
)
mock_get_access_token = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._get_access_token',
return_value='token'
)

mock_upload_template_response = MagicMock()
mock_upload_template_response.headers = {
'X-Template-Hash': 'hash_code'
}
mock_upload_template_response.status_code = 200
mock_post_upload_template = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._post_upload_template',
return_value=mock_upload_template_response
)

engagement = factory_engagement_model()
TestWidgetInfo.widget_subscribe['engagement_id'] = engagement.id
widget = factory_widget_model(TestWidgetInfo.widget_subscribe)
form_data = TestCACForm.form_data.value

headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.no_role)

rv = create_widget_subscription(client, jwt, widget.id, headers)
assert rv.status_code == HTTPStatus.OK.value

# Sending POST request for CAC
rv = create_cac_form_submission(client, jwt, engagement.id, widget.id, form_data, headers)
assert rv.status_code == HTTPStatus.OK.value

headers = factory_auth_header(jwt=jwt, claims=claims)
rv = client.get(f'/api/engagements/{engagement.id}/cacform/sheet',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == 200
mock_post_generate_document.assert_called()
mock_get_access_token.assert_called()
mock_post_upload_template.assert_called()

with patch.object(CACFormService, 'export_cac_form_submissions_to_spread_sheet', side_effect=side_effect):
rv = client.get(f'/api/engagements/{engagement.id}/cacform/sheet',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == expected_status
88 changes: 85 additions & 3 deletions met-api/tests/unit/api/test_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from met_api.constants.membership_type import MembershipType
from met_api.constants.staff_note_type import StaffNoteType
from met_api.services.comment_service import CommentService
from met_api.utils import notification
from met_api.utils.enums import ContentType
from tests.utilities.factory_scenarios import TestJwtClaims
Expand All @@ -47,6 +48,11 @@ def test_get_comments(client, jwt, session): # pylint:disable=unused-argument
rv = client.get(f'/api/comments/survey/{survey.id}', headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == 200

with patch.object(CommentService, 'get_comments_paginated', side_effect=ValueError('Test error')):
rv = client.get(f'/api/comments/survey/{survey.id}', headers=headers, content_type=ContentType.JSON.value)

assert rv.status_code == HTTPStatus.INTERNAL_SERVER_ERROR


def test_review_comment(client, jwt, session): # pylint:disable=unused-argument
"""Assert that a comment can be reviewed."""
Expand Down Expand Up @@ -175,9 +181,9 @@ def test_review_comment_review_note(client, jwt, session): # pylint:disable=unu
mock_mail.assert_called()


def test_get_comments_spreadsheet(mocker, client, jwt, session,
setup_admin_user_and_claims): # pylint:disable=unused-argument
"""Assert that comments sheet can be fetched."""
def test_get_comments_spreadsheet_staff(mocker, client, jwt, session,
setup_admin_user_and_claims): # pylint:disable=unused-argument
"""Assert that staff comments sheet can be fetched."""
user, claims = setup_admin_user_and_claims

mock_post_generate_document_response = MagicMock()
Expand Down Expand Up @@ -214,3 +220,79 @@ def test_get_comments_spreadsheet(mocker, client, jwt, session,
mock_post_generate_document.assert_called()
mock_get_access_token.assert_called()
mock_post_upload_template.assert_called()

with patch.object(CommentService, 'export_comments_to_spread_sheet_staff',
side_effect=ValueError('Test error')):
rv = client.get(f'/api/comments/survey/{survey.id}/sheet/staff',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == HTTPStatus.INTERNAL_SERVER_ERROR


def test_get_comments_spreadsheet_proponent(mocker, client, jwt, session,
setup_admin_user_and_claims): # pylint:disable=unused-argument
"""Assert that proponent comments sheet can be fetched."""
user, claims = setup_admin_user_and_claims

mock_post_generate_document_response = MagicMock()
mock_post_generate_document_response.content = b'mock data'
mock_post_generate_document_response.headers = {}
mock_post_generate_document_response.status_code = 200
mock_post_generate_document = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._post_generate_document',
return_value=mock_post_generate_document_response
)
mock_get_access_token = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._get_access_token',
return_value='token'
)

mock_upload_template_response = MagicMock()
mock_upload_template_response.headers = {
'X-Template-Hash': 'hash_code'
}
mock_upload_template_response.status_code = 200
mock_post_upload_template = mocker.patch(
'met_api.services.cdogs_api_service.CdogsApiService._post_upload_template',
return_value=mock_upload_template_response
)

participant = factory_participant_model()
survey, eng = factory_survey_and_eng_model()
submission = factory_submission_model(survey.id, eng.id, participant.id)
factory_comment_model(survey.id, submission.id)
headers = factory_auth_header(jwt=jwt, claims=claims)
rv = client.get(f'/api/comments/survey/{survey.id}/sheet/proponent',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == 200
mock_post_generate_document.assert_called()
mock_get_access_token.assert_called()
mock_post_upload_template.assert_called()

with patch.object(CommentService, 'export_comments_to_spread_sheet_proponent',
side_effect=ValueError('Test error')):
rv = client.get(f'/api/comments/survey/{survey.id}/sheet/proponent',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == HTTPStatus.INTERNAL_SERVER_ERROR


def test_get_comments_spreadsheet_without_role(mocker, client, jwt, session): # pylint:disable=unused-argument
"""Assert that proponent comments sheet can be fetched."""
mock_post_generate_document_response = MagicMock()
mock_post_generate_document_response.content = b'mock data'
mock_post_generate_document_response.headers = {}
mock_post_generate_document_response.status_code = 200

mock_upload_template_response = MagicMock()
mock_upload_template_response.headers = {
'X-Template-Hash': 'hash_code'
}
mock_upload_template_response.status_code = 200

participant = factory_participant_model()
survey, eng = factory_survey_and_eng_model()
submission = factory_submission_model(survey.id, eng.id, participant.id)
factory_comment_model(survey.id, submission.id)
headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.public_user_role)
rv = client.get(f'/api/comments/survey/{survey.id}/sheet/staff',
headers=headers, content_type=ContentType.JSON.value)
assert rv.status_code == HTTPStatus.UNAUTHORIZED, 'Not a team member.So throws exception.'
Loading

0 comments on commit 49819b6

Please sign in to comment.