-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add more semantics to API exceptions related to subsidy fulfillment #207
Open
iloveagent57
wants to merge
1
commit into
main
Choose a base branch
from
aed/redeem-error-msg
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
""" | ||
Version 1 API Exceptions. | ||
""" | ||
from rest_framework import status | ||
from rest_framework.exceptions import APIException | ||
|
||
from enterprise_access.apps.api_client.lms_client import LmsApiClient | ||
from enterprise_access.apps.subsidy_access_policy import constants | ||
|
||
|
||
class RedemptionRequestException(APIException): | ||
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY | ||
default_detail = 'Could not redeem' | ||
|
||
|
||
class SubsidyAPIRedemptionRequestException(RedemptionRequestException): | ||
""" | ||
An API exception that has a response payload structured like | ||
{ | ||
'code': 'some_error_code', | ||
'detail': { | ||
'reason': 'reason_for_error', | ||
'user_message': 'User friendly string describing the error.', | ||
# additional metadata describing the error, possibly including admin emails. | ||
'metadata': { | ||
'key': 'value', | ||
} | ||
} | ||
} | ||
|
||
There are some sane defaults set at initialization for the reason, code, and user_message | ||
values. | ||
""" | ||
default_detail = 'Error redeeming through Subsidy API' | ||
default_code = constants.SubsidyRedemptionErrorCodes.DEFAULT_ERROR | ||
|
||
# Custom keys of the `detail` field returned in the response payload. | ||
default_reason = constants.SubsidyRedemptionErrorReasons.DEFAULT_REASON | ||
default_user_message = constants.SubsidyRedemptionErrorReasons.USER_MESSAGES_BY_REASON[default_reason] | ||
|
||
def __init__(self, code=None, detail=None, policy=None, subsidy_api_error=None): | ||
""" | ||
Initializes all of the attributes of this exception instance. | ||
|
||
args: | ||
code (str): A reusable error code constant. | ||
detail ([list,str,dict]): Details about the exception we're raising. | ||
policy (SubsidyAccessPolicy): A policy object, from which we can fetch admin email addresses. | ||
subsidy_api_error (SubsidyAPIHTTPError): The exception object that was caught, from which | ||
we can infer more specific causes about the redemption error this exception encapsulates. | ||
""" | ||
super().__init__(code=code, detail=detail) | ||
|
||
self.reason = self.default_reason | ||
self.user_message = self.default_user_message | ||
self.metadata = {} | ||
|
||
if policy and subsidy_api_error: | ||
try: | ||
self._build_subsidy_api_error_payload(policy, subsidy_api_error) | ||
except Exception: # pylint: disable=broad-except | ||
self.metadata = { | ||
'subsidy_error_detail_raw': str(subsidy_api_error.error_response.content), | ||
} | ||
|
||
self.detail = { | ||
'code': self.code, | ||
'detail': { | ||
'reason': self.reason, | ||
'user_message': self.user_message, | ||
'metadata': self.metadata, | ||
} | ||
} | ||
|
||
def _build_subsidy_api_error_payload(self, policy, subsidy_api_error): | ||
""" | ||
Helper to build error response payload on Subsidy API errors. | ||
""" | ||
subsidy_error_detail = subsidy_api_error.error_payload().get('detail') | ||
subsidy_error_code = subsidy_api_error.error_payload().get('code') | ||
|
||
self.metadata = { | ||
'enterprise_administrators': LmsApiClient().get_enterprise_customer_data( | ||
policy.enterprise_customer_uuid | ||
).get('admin_users') | ||
} | ||
|
||
# We currently only have enough data to say more specific things | ||
# about fulfillment errors during subsidy API redemption. | ||
if subsidy_error_code == constants.SubsidyRedemptionErrorCodes.FULFILLMENT_ERROR: | ||
self._set_subsidy_fulfillment_error_reason(subsidy_error_detail) | ||
|
||
def _set_subsidy_fulfillment_error_reason(self, subsidy_error_detail): | ||
""" | ||
Helper to set the reason, user_message, and metadata | ||
for the given subsidy_error_detail. | ||
""" | ||
self.metadata['subsidy_error_detail'] = subsidy_error_detail | ||
self.reason = constants.SubsidyFulfillmentErrorReasons.DEFAULT_REASON | ||
|
||
if subsidy_error_detail: | ||
message_string = self._get_subsidy_fulfillment_error_message(subsidy_error_detail) | ||
if cause_of_message := constants.SubsidyFulfillmentErrorReasons.get_cause_from_error_message( | ||
message_string | ||
): | ||
self.reason = cause_of_message | ||
# pylint: disable=attribute-defined-outside-init | ||
self.code = constants.SubsidyRedemptionErrorCodes.FULFILLMENT_ERROR | ||
|
||
self.user_message = constants.SubsidyFulfillmentErrorReasons.USER_MESSAGES_BY_REASON.get(self.reason) | ||
|
||
def _get_subsidy_fulfillment_error_message(self, subsidy_error_detail): | ||
""" | ||
``subsidy_error_detail`` is either a string describing an error message, | ||
a dict with a "message" key describing an error message, or a list of such | ||
dicts. This helper method widdles any of those things down into a single | ||
error message string. | ||
""" | ||
if isinstance(subsidy_error_detail, str): | ||
return subsidy_error_detail | ||
|
||
subsidy_message_dict = subsidy_error_detail | ||
if isinstance(subsidy_error_detail, list): | ||
subsidy_message_dict = subsidy_error_detail[0] | ||
|
||
return subsidy_message_dict.get('message') | ||
|
||
|
||
class SubsidyAccessPolicyLockedException(APIException): | ||
""" | ||
Throw this exception when an attempt to acquire a policy lock failed because it was already locked by another agent. | ||
|
||
Note: status.HTTP_423_LOCKED is NOT acceptable as a status code for delivery to web browsers. According to Mozilla: | ||
|
||
> The ability to lock a resource is specific to some WebDAV servers. Browsers accessing web pages will never | ||
> encounter this status code; in the erroneous cases it happens, they will handle it as a generic 400 status code. | ||
|
||
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/423 | ||
|
||
HTTP 429 Too Many Requests is the next best thing, and implies retryability. | ||
""" | ||
status_code = status.HTTP_429_TOO_MANY_REQUESTS | ||
default_detail = 'Enrollment currently locked for this subsidy access policy.' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
from uuid import UUID, uuid4 | ||
|
||
import ddt | ||
import requests | ||
from django.conf import settings | ||
from rest_framework import status | ||
from rest_framework.reverse import reverse | ||
|
@@ -22,6 +23,8 @@ | |
AccessMethods, | ||
MissingSubsidyAccessReasonUserMessages, | ||
PolicyTypes, | ||
SubsidyFulfillmentErrorReasons, | ||
SubsidyRedemptionErrorCodes, | ||
TransactionStateChoices | ||
) | ||
from enterprise_access.apps.subsidy_access_policy.tests.factories import ( | ||
|
@@ -682,6 +685,65 @@ def test_redeem_policy(self, mock_transactions_cache_for_learner): # pylint: di | |
), | ||
) | ||
|
||
@mock.patch('enterprise_access.apps.subsidy_access_policy.models.get_and_cache_transactions_for_learner') | ||
@mock.patch('enterprise_access.apps.api.v1.exceptions.LmsApiClient') | ||
@ddt.data( | ||
{ | ||
'subsidy_error_code': 'fulfillment_error', | ||
'subsidy_error_detail': [ | ||
{'message': 'woozit duplicate order woohoo!'}, | ||
], | ||
'expected_redeem_error_detail': { | ||
'reason': SubsidyFulfillmentErrorReasons.DUPLICATE_FULFILLMENT, | ||
'user_message': SubsidyFulfillmentErrorReasons.USER_MESSAGES_BY_REASON[ | ||
SubsidyFulfillmentErrorReasons.DUPLICATE_FULFILLMENT | ||
], | ||
'metadata': { | ||
'enterprise_administrators': [{'email': '[email protected]'}], | ||
'subsidy_error_detail': [ | ||
{'message': 'woozit duplicate order woohoo!'} | ||
], | ||
}, | ||
}, | ||
'expected_redeem_error_code': SubsidyRedemptionErrorCodes.FULFILLMENT_ERROR, | ||
}, | ||
) | ||
@ddt.unpack | ||
def test_redeem_policy_subsidy_api_error( | ||
self, mock_lms_api_client, mock_transactions_cache_for_learner, # pylint: disable=unused-argument | ||
subsidy_error_code, subsidy_error_detail, | ||
expected_redeem_error_detail, expected_redeem_error_code | ||
): | ||
""" | ||
Verify that SubsidyAccessPolicyRedeemViewset redeem endpoint returns a well-structured | ||
error response payload when the subsidy API call to redeem/fulfill responds with an error. | ||
""" | ||
mock_lms_api_client().get_enterprise_customer_data.return_value = { | ||
'slug': 'the-slug', | ||
'admin_users': [{'email': '[email protected]'}], | ||
} | ||
self.mock_get_content_metadata.return_value = {'content_price': 123} | ||
mock_response = mock.MagicMock() | ||
mock_response.json.return_value = { | ||
'code': subsidy_error_code, | ||
'detail': subsidy_error_detail, | ||
} | ||
self.redeemable_policy.subsidy_client.create_subsidy_transaction.side_effect = requests.exceptions.HTTPError( | ||
response=mock_response | ||
) | ||
|
||
payload = { | ||
'lms_user_id': 1234, | ||
'content_key': 'course-v1:edX+edXPrivacy101+3T2020', | ||
} | ||
|
||
response = self.client.post(self.subsidy_access_policy_redeem_endpoint, payload) | ||
|
||
response_json = self.load_json(response.content) | ||
self.maxDiff = None | ||
self.assertEqual(response_json['detail'], expected_redeem_error_detail) | ||
self.assertEqual(response_json['code'], expected_redeem_error_code) | ||
|
||
@mock.patch('enterprise_access.apps.subsidy_access_policy.models.get_and_cache_transactions_for_learner') | ||
def test_redeem_policy_with_metadata(self, mock_transactions_cache_for_learner): # pylint: disable=unused-argument | ||
""" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this just the result of the subsidy API being indecisive about error formatting and being written by >1 person?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oof yes, can we fix the offending call?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wrote it to be defensive about the types of messages that can exist from a DRF APIException: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py