mirror of
https://github.com/GSA/notifications-api.git
synced 2026-05-05 08:40:29 -04:00
notify-api-412 use black to enforce python style standards
This commit is contained in:
@@ -5,13 +5,13 @@ from app import aws_cloudwatch_client
|
||||
|
||||
|
||||
def test_check_sms_no_event_error_condition(notify_api, mocker):
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, "_client", create=True)
|
||||
# TODO
|
||||
# we do this to get the AWS account number, and it seems like unit tests locally have
|
||||
# access to the env variables but when we push the PR they do not. Is there a better way to get it?
|
||||
mocker.patch.dict('os.environ', {"SES_DOMAIN_ARN": "1111:"})
|
||||
message_id = 'aaa'
|
||||
notification_id = 'bbb'
|
||||
mocker.patch.dict("os.environ", {"SES_DOMAIN_ARN": "1111:"})
|
||||
message_id = "aaa"
|
||||
notification_id = "bbb"
|
||||
boto_mock.filter_log_events.return_value = []
|
||||
with notify_api.app_context():
|
||||
aws_cloudwatch_client.init_app(current_app)
|
||||
@@ -23,30 +23,28 @@ def test_check_sms_no_event_error_condition(notify_api, mocker):
|
||||
|
||||
|
||||
def side_effect(filterPattern, logGroupName, startTime, endTime):
|
||||
if "Failure" in logGroupName and 'fail' in filterPattern:
|
||||
if "Failure" in logGroupName and "fail" in filterPattern:
|
||||
return {
|
||||
"events":
|
||||
[
|
||||
{
|
||||
'logStreamName': '89db9712-c6d1-49f9-be7c-4caa7ed9efb1',
|
||||
'message': '{"delivery":{"destination":"+1661","providerResponse":"Invalid phone number"}}',
|
||||
'eventId': '37535432778099870001723210579798865345508698025292922880'
|
||||
}
|
||||
]
|
||||
"events": [
|
||||
{
|
||||
"logStreamName": "89db9712-c6d1-49f9-be7c-4caa7ed9efb1",
|
||||
"message": '{"delivery":{"destination":"+1661","providerResponse":"Invalid phone number"}}',
|
||||
"eventId": "37535432778099870001723210579798865345508698025292922880",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
elif 'succeed' in filterPattern:
|
||||
elif "succeed" in filterPattern:
|
||||
return {
|
||||
"events":
|
||||
[
|
||||
{
|
||||
'logStreamName': '89db9712-c6d1-49f9-be7c-4caa7ed9efb1',
|
||||
'timestamp': 1683147017911,
|
||||
'message': '{"delivery":{"destination":"+1661","providerResponse":"Phone accepted msg"}}',
|
||||
'ingestionTime': 1683147018026,
|
||||
'eventId': '37535432778099870001723210579798865345508698025292922880'
|
||||
}
|
||||
]
|
||||
"events": [
|
||||
{
|
||||
"logStreamName": "89db9712-c6d1-49f9-be7c-4caa7ed9efb1",
|
||||
"timestamp": 1683147017911,
|
||||
"message": '{"delivery":{"destination":"+1661","providerResponse":"Phone accepted msg"}}',
|
||||
"ingestionTime": 1683147018026,
|
||||
"eventId": "37535432778099870001723210579798865345508698025292922880",
|
||||
}
|
||||
]
|
||||
}
|
||||
else:
|
||||
return {"events": []}
|
||||
@@ -54,37 +52,37 @@ def side_effect(filterPattern, logGroupName, startTime, endTime):
|
||||
|
||||
def test_check_sms_success(notify_api, mocker):
|
||||
aws_cloudwatch_client.init_app(current_app)
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, "_client", create=True)
|
||||
boto_mock.filter_log_events.side_effect = side_effect
|
||||
mocker.patch.dict('os.environ', {"SES_DOMAIN_ARN": "1111:"})
|
||||
mocker.patch.dict("os.environ", {"SES_DOMAIN_ARN": "1111:"})
|
||||
|
||||
message_id = 'succeed'
|
||||
notification_id = 'ccc'
|
||||
message_id = "succeed"
|
||||
notification_id = "ccc"
|
||||
with notify_api.app_context():
|
||||
aws_cloudwatch_client.check_sms(message_id, notification_id, 1000000000000)
|
||||
|
||||
# We check the 'success' log group first and if we find the message_id, we are done, so there is only 1 call
|
||||
assert boto_mock.filter_log_events.call_count == 1
|
||||
mock_call = str(boto_mock.filter_log_events.mock_calls[0])
|
||||
assert 'Failure' not in mock_call
|
||||
assert 'succeed' in mock_call
|
||||
assert 'notification.messageId' in mock_call
|
||||
assert "Failure" not in mock_call
|
||||
assert "succeed" in mock_call
|
||||
assert "notification.messageId" in mock_call
|
||||
|
||||
|
||||
def test_check_sms_failure(notify_api, mocker):
|
||||
aws_cloudwatch_client.init_app(current_app)
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_cloudwatch_client, "_client", create=True)
|
||||
boto_mock.filter_log_events.side_effect = side_effect
|
||||
mocker.patch.dict('os.environ', {"SES_DOMAIN_ARN": "1111:"})
|
||||
mocker.patch.dict("os.environ", {"SES_DOMAIN_ARN": "1111:"})
|
||||
|
||||
message_id = 'fail'
|
||||
notification_id = 'bbb'
|
||||
message_id = "fail"
|
||||
notification_id = "bbb"
|
||||
with notify_api.app_context():
|
||||
aws_cloudwatch_client.check_sms(message_id, notification_id, 1000000000000)
|
||||
|
||||
# We check the 'success' log group and find nothing, so we then check the 'fail' log group -- two calls.
|
||||
assert boto_mock.filter_log_events.call_count == 2
|
||||
mock_call = str(boto_mock.filter_log_events.mock_calls[1])
|
||||
assert 'Failure' in mock_call
|
||||
assert 'fail' in mock_call
|
||||
assert 'notification.messageId' in mock_call
|
||||
assert "Failure" in mock_call
|
||||
assert "fail" in mock_call
|
||||
assert "notification.messageId" in mock_call
|
||||
|
||||
@@ -15,188 +15,194 @@ from app.clients.email.aws_ses import (
|
||||
|
||||
|
||||
def test_should_return_correct_details_for_delivery():
|
||||
response_dict = get_aws_responses('Delivery')
|
||||
assert response_dict['message'] == 'Delivered'
|
||||
assert response_dict['notification_status'] == 'delivered'
|
||||
assert response_dict['notification_statistics_status'] == 'delivered'
|
||||
assert response_dict['success']
|
||||
response_dict = get_aws_responses("Delivery")
|
||||
assert response_dict["message"] == "Delivered"
|
||||
assert response_dict["notification_status"] == "delivered"
|
||||
assert response_dict["notification_statistics_status"] == "delivered"
|
||||
assert response_dict["success"]
|
||||
|
||||
|
||||
def test_should_return_correct_details_for_hard_bounced():
|
||||
response_dict = get_aws_responses('Permanent')
|
||||
assert response_dict['message'] == 'Hard bounced'
|
||||
assert response_dict['notification_status'] == 'permanent-failure'
|
||||
assert response_dict['notification_statistics_status'] == 'failure'
|
||||
assert not response_dict['success']
|
||||
response_dict = get_aws_responses("Permanent")
|
||||
assert response_dict["message"] == "Hard bounced"
|
||||
assert response_dict["notification_status"] == "permanent-failure"
|
||||
assert response_dict["notification_statistics_status"] == "failure"
|
||||
assert not response_dict["success"]
|
||||
|
||||
|
||||
def test_should_return_correct_details_for_soft_bounced():
|
||||
response_dict = get_aws_responses('Temporary')
|
||||
assert response_dict['message'] == 'Soft bounced'
|
||||
assert response_dict['notification_status'] == 'temporary-failure'
|
||||
assert response_dict['notification_statistics_status'] == 'failure'
|
||||
assert not response_dict['success']
|
||||
response_dict = get_aws_responses("Temporary")
|
||||
assert response_dict["message"] == "Soft bounced"
|
||||
assert response_dict["notification_status"] == "temporary-failure"
|
||||
assert response_dict["notification_statistics_status"] == "failure"
|
||||
assert not response_dict["success"]
|
||||
|
||||
|
||||
def test_should_return_correct_details_for_complaint():
|
||||
response_dict = get_aws_responses('Complaint')
|
||||
assert response_dict['message'] == 'Complaint'
|
||||
assert response_dict['notification_status'] == 'delivered'
|
||||
assert response_dict['notification_statistics_status'] == 'delivered'
|
||||
assert response_dict['success']
|
||||
response_dict = get_aws_responses("Complaint")
|
||||
assert response_dict["message"] == "Complaint"
|
||||
assert response_dict["notification_status"] == "delivered"
|
||||
assert response_dict["notification_statistics_status"] == "delivered"
|
||||
assert response_dict["success"]
|
||||
|
||||
|
||||
def test_should_be_none_if_unrecognised_status_code():
|
||||
with pytest.raises(KeyError) as e:
|
||||
get_aws_responses('99')
|
||||
assert '99' in str(e.value)
|
||||
get_aws_responses("99")
|
||||
assert "99" in str(e.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reply_to_address, expected_value', [
|
||||
(None, []),
|
||||
('foo@bar.com', ['foo@bar.com']),
|
||||
('føøøø@bååååår.com', ['føøøø@xn--br-yiaaaaa.com'])
|
||||
], ids=['empty', 'single_email', 'punycode'])
|
||||
def test_send_email_handles_reply_to_address(notify_api, mocker, reply_to_address, expected_value):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
@pytest.mark.parametrize(
|
||||
"reply_to_address, expected_value",
|
||||
[
|
||||
(None, []),
|
||||
("foo@bar.com", ["foo@bar.com"]),
|
||||
("føøøø@bååååår.com", ["føøøø@xn--br-yiaaaaa.com"]),
|
||||
],
|
||||
ids=["empty", "single_email", "punycode"],
|
||||
)
|
||||
def test_send_email_handles_reply_to_address(
|
||||
notify_api, mocker, reply_to_address, expected_value
|
||||
):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
|
||||
with notify_api.app_context():
|
||||
aws_ses_client.send_email(
|
||||
source=Mock(),
|
||||
to_addresses='to@address.com',
|
||||
to_addresses="to@address.com",
|
||||
subject=Mock(),
|
||||
body=Mock(),
|
||||
reply_to_address=reply_to_address
|
||||
reply_to_address=reply_to_address,
|
||||
)
|
||||
|
||||
boto_mock.send_email.assert_called_once_with(
|
||||
Source=ANY,
|
||||
Destination=ANY,
|
||||
Message=ANY,
|
||||
ReplyToAddresses=expected_value
|
||||
Source=ANY, Destination=ANY, Message=ANY, ReplyToAddresses=expected_value
|
||||
)
|
||||
|
||||
|
||||
def test_send_email_handles_punycode_to_address(notify_api, mocker):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
|
||||
with notify_api.app_context():
|
||||
aws_ses_client.send_email(
|
||||
Mock(),
|
||||
to_addresses='føøøø@bååååår.com',
|
||||
subject=Mock(),
|
||||
body=Mock()
|
||||
Mock(), to_addresses="føøøø@bååååår.com", subject=Mock(), body=Mock()
|
||||
)
|
||||
|
||||
boto_mock.send_email.assert_called_once_with(
|
||||
Source=ANY,
|
||||
Destination={'ToAddresses': ['føøøø@xn--br-yiaaaaa.com'], 'CcAddresses': [], 'BccAddresses': []},
|
||||
Destination={
|
||||
"ToAddresses": ["føøøø@xn--br-yiaaaaa.com"],
|
||||
"CcAddresses": [],
|
||||
"BccAddresses": [],
|
||||
},
|
||||
Message=ANY,
|
||||
ReplyToAddresses=ANY
|
||||
ReplyToAddresses=ANY,
|
||||
)
|
||||
|
||||
|
||||
def test_send_email_raises_invalid_parameter_value_error_as_EmailClientNonRetryableException(mocker):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
def test_send_email_raises_invalid_parameter_value_error_as_EmailClientNonRetryableException(
|
||||
mocker,
|
||||
):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
error_response = {
|
||||
'Error': {
|
||||
'Code': 'InvalidParameterValue',
|
||||
'Message': 'some error message from amazon',
|
||||
'Type': 'Sender'
|
||||
"Error": {
|
||||
"Code": "InvalidParameterValue",
|
||||
"Message": "some error message from amazon",
|
||||
"Type": "Sender",
|
||||
}
|
||||
}
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(error_response, 'opname')
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(
|
||||
error_response, "opname"
|
||||
)
|
||||
|
||||
with pytest.raises(EmailClientNonRetryableException) as excinfo:
|
||||
aws_ses_client.send_email(
|
||||
source=Mock(),
|
||||
to_addresses='definitely@invalid_email.com',
|
||||
to_addresses="definitely@invalid_email.com",
|
||||
subject=Mock(),
|
||||
body=Mock()
|
||||
body=Mock(),
|
||||
)
|
||||
|
||||
assert 'some error message from amazon' in str(excinfo.value)
|
||||
assert "some error message from amazon" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_send_email_raises_send_rate_throttling_as_AwsSesClientThrottlingSendRateException(mocker):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
def test_send_email_raises_send_rate_throttling_as_AwsSesClientThrottlingSendRateException(
|
||||
mocker,
|
||||
):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
error_response = {
|
||||
'Error': {
|
||||
'Code': 'Throttling',
|
||||
'Message': 'Maximum sending rate exceeded.',
|
||||
'Type': 'Sender'
|
||||
"Error": {
|
||||
"Code": "Throttling",
|
||||
"Message": "Maximum sending rate exceeded.",
|
||||
"Type": "Sender",
|
||||
}
|
||||
}
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(error_response, 'opname')
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(
|
||||
error_response, "opname"
|
||||
)
|
||||
|
||||
with pytest.raises(AwsSesClientThrottlingSendRateException):
|
||||
aws_ses_client.send_email(
|
||||
source=Mock(),
|
||||
to_addresses='foo@bar.com',
|
||||
subject=Mock(),
|
||||
body=Mock()
|
||||
source=Mock(), to_addresses="foo@bar.com", subject=Mock(), body=Mock()
|
||||
)
|
||||
|
||||
|
||||
def test_send_email_does_not_raise_AwsSesClientThrottlingSendRateException_if_non_send_rate_throttling(mocker):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
def test_send_email_does_not_raise_AwsSesClientThrottlingSendRateException_if_non_send_rate_throttling(
|
||||
mocker,
|
||||
):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
error_response = {
|
||||
'Error': {
|
||||
'Code': 'Throttling',
|
||||
'Message': 'Daily message quota exceeded',
|
||||
'Type': 'Sender'
|
||||
"Error": {
|
||||
"Code": "Throttling",
|
||||
"Message": "Daily message quota exceeded",
|
||||
"Type": "Sender",
|
||||
}
|
||||
}
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(error_response, 'opname')
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(
|
||||
error_response, "opname"
|
||||
)
|
||||
|
||||
with pytest.raises(AwsSesClientException):
|
||||
aws_ses_client.send_email(
|
||||
source=Mock(),
|
||||
to_addresses='foo@bar.com',
|
||||
subject=Mock(),
|
||||
body=Mock()
|
||||
source=Mock(), to_addresses="foo@bar.com", subject=Mock(), body=Mock()
|
||||
)
|
||||
|
||||
|
||||
def test_send_email_raises_other_errs_as_AwsSesClientException(mocker):
|
||||
boto_mock = mocker.patch.object(aws_ses_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)
|
||||
error_response = {
|
||||
'Error': {
|
||||
'Code': 'ServiceUnavailable',
|
||||
'Message': 'some error message from amazon',
|
||||
'Type': 'Sender'
|
||||
"Error": {
|
||||
"Code": "ServiceUnavailable",
|
||||
"Message": "some error message from amazon",
|
||||
"Type": "Sender",
|
||||
}
|
||||
}
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(error_response, 'opname')
|
||||
boto_mock.send_email.side_effect = botocore.exceptions.ClientError(
|
||||
error_response, "opname"
|
||||
)
|
||||
|
||||
with pytest.raises(AwsSesClientException) as excinfo:
|
||||
aws_ses_client.send_email(
|
||||
source=Mock(),
|
||||
to_addresses='foo@bar.com',
|
||||
subject=Mock(),
|
||||
body=Mock()
|
||||
source=Mock(), to_addresses="foo@bar.com", subject=Mock(), body=Mock()
|
||||
)
|
||||
|
||||
assert 'some error message from amazon' in str(excinfo.value)
|
||||
assert "some error message from amazon" in str(excinfo.value)
|
||||
|
||||
|
||||
@mock.patch('app.clients.email.aws_ses_stub.request')
|
||||
@mock.patch("app.clients.email.aws_ses_stub.request")
|
||||
def test_send_email_stub(mock_request):
|
||||
mock_request.return_value = FakeResponse()
|
||||
stub = AwsSesStubClient()
|
||||
stub.init_app("fake")
|
||||
answer = stub.send_email(
|
||||
'fake@fake.gov',
|
||||
'recipient@wherever.com',
|
||||
'TestTest',
|
||||
'TestBody')
|
||||
"fake@fake.gov", "recipient@wherever.com", "TestTest", "TestBody"
|
||||
)
|
||||
print(answer)
|
||||
assert answer == 'SomeId'
|
||||
assert answer == "SomeId"
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self):
|
||||
|
||||
t = {"MessageId": "SomeId"}
|
||||
self.text = json.dumps(t)
|
||||
|
||||
|
||||
@@ -4,25 +4,33 @@ from app import aws_sns_client
|
||||
|
||||
|
||||
def test_send_sms_successful_returns_aws_sns_response(notify_api, mocker):
|
||||
boto_mock = mocker.patch.object(aws_sns_client, '_client', create=True)
|
||||
boto_mock = mocker.patch.object(aws_sns_client, "_client", create=True)
|
||||
to = "6135555555"
|
||||
content = reference = 'foo'
|
||||
content = reference = "foo"
|
||||
with notify_api.app_context():
|
||||
aws_sns_client.send_sms(to, content, reference)
|
||||
boto_mock.publish.assert_called_once_with(
|
||||
PhoneNumber="+16135555555",
|
||||
Message=content,
|
||||
MessageAttributes={
|
||||
'AWS.SNS.SMS.SMSType': {'DataType': 'String', 'StringValue': 'Transactional'},
|
||||
'AWS.MM.SMS.OriginationNumber': {'DataType': 'String', 'StringValue': '+18556438890'}
|
||||
}
|
||||
"AWS.SNS.SMS.SMSType": {
|
||||
"DataType": "String",
|
||||
"StringValue": "Transactional",
|
||||
},
|
||||
"AWS.MM.SMS.OriginationNumber": {
|
||||
"DataType": "String",
|
||||
"StringValue": "+18556438890",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_send_sms_returns_raises_error_if_there_is_no_valid_number_is_found(notify_api, mocker):
|
||||
mocker.patch.object(aws_sns_client, '_client', create=True)
|
||||
def test_send_sms_returns_raises_error_if_there_is_no_valid_number_is_found(
|
||||
notify_api, mocker
|
||||
):
|
||||
mocker.patch.object(aws_sns_client, "_client", create=True)
|
||||
to = ""
|
||||
content = reference = 'foo'
|
||||
content = reference = "foo"
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
aws_sns_client.send_sms(to, content, reference)
|
||||
assert 'No valid numbers found for SMS delivery' in str(excinfo.value)
|
||||
assert "No valid numbers found for SMS delivery" in str(excinfo.value)
|
||||
|
||||
@@ -8,68 +8,99 @@ from app.clients.document_download import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
@pytest.fixture(scope="function")
|
||||
def document_download(client, mocker):
|
||||
client = DocumentDownloadClient()
|
||||
current_app = mocker.Mock(config={
|
||||
'DOCUMENT_DOWNLOAD_API_HOST': 'https://document-download',
|
||||
'DOCUMENT_DOWNLOAD_API_KEY': 'test-key'
|
||||
})
|
||||
current_app = mocker.Mock(
|
||||
config={
|
||||
"DOCUMENT_DOWNLOAD_API_HOST": "https://document-download",
|
||||
"DOCUMENT_DOWNLOAD_API_KEY": "test-key",
|
||||
}
|
||||
)
|
||||
client.init_app(current_app)
|
||||
return client
|
||||
|
||||
|
||||
def test_get_upload_url(document_download):
|
||||
assert document_download.get_upload_url('service-id') == 'https://document-download/services/service-id/documents'
|
||||
assert (
|
||||
document_download.get_upload_url("service-id")
|
||||
== "https://document-download/services/service-id/documents"
|
||||
)
|
||||
|
||||
|
||||
def test_upload_document(document_download):
|
||||
with requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://document-download/services/service-id/documents', json={
|
||||
'document': {'url': 'https://document-download/services/service-id/documents/uploaded-url'}
|
||||
}, request_headers={
|
||||
'Authorization': 'Bearer test-key',
|
||||
}, status_code=201)
|
||||
request_mock.post(
|
||||
"https://document-download/services/service-id/documents",
|
||||
json={
|
||||
"document": {
|
||||
"url": "https://document-download/services/service-id/documents/uploaded-url"
|
||||
}
|
||||
},
|
||||
request_headers={
|
||||
"Authorization": "Bearer test-key",
|
||||
},
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
resp = document_download.upload_document('service-id', 'abababab')
|
||||
resp = document_download.upload_document("service-id", "abababab")
|
||||
|
||||
assert resp == 'https://document-download/services/service-id/documents/uploaded-url'
|
||||
assert (
|
||||
resp == "https://document-download/services/service-id/documents/uploaded-url"
|
||||
)
|
||||
|
||||
|
||||
def test_should_raise_400s_as_DocumentDownloadErrors(document_download):
|
||||
with pytest.raises(DocumentDownloadError) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://document-download/services/service-id/documents', json={
|
||||
'error': 'Invalid mime type'
|
||||
}, status_code=400)
|
||||
with pytest.raises(
|
||||
DocumentDownloadError
|
||||
) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
request_mock.post(
|
||||
"https://document-download/services/service-id/documents",
|
||||
json={"error": "Invalid mime type"},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
document_download.upload_document('service-id', 'abababab')
|
||||
document_download.upload_document("service-id", "abababab")
|
||||
|
||||
assert excinfo.value.message == 'Invalid mime type'
|
||||
assert excinfo.value.message == "Invalid mime type"
|
||||
assert excinfo.value.status_code == 400
|
||||
|
||||
|
||||
def test_should_raise_non_400_statuses_as_exceptions(document_download):
|
||||
with pytest.raises(expected_exception=Exception) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
with pytest.raises(
|
||||
expected_exception=Exception
|
||||
) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
request_mock.post(
|
||||
'https://document-download/services/service-id/documents',
|
||||
json={'error': 'Auth Error Of Some Kind'},
|
||||
status_code=403
|
||||
"https://document-download/services/service-id/documents",
|
||||
json={"error": "Auth Error Of Some Kind"},
|
||||
status_code=403,
|
||||
)
|
||||
|
||||
document_download.upload_document('service-id', 'abababab')
|
||||
document_download.upload_document("service-id", "abababab")
|
||||
|
||||
assert type(excinfo.value) == Exception # make sure it's a base exception, so will be handled as a 500 by v2 api
|
||||
assert str(excinfo.value) == 'Unhandled document download error: {"error": "Auth Error Of Some Kind"}'
|
||||
assert (
|
||||
type(excinfo.value) == Exception
|
||||
) # make sure it's a base exception, so will be handled as a 500 by v2 api
|
||||
assert (
|
||||
str(excinfo.value)
|
||||
== 'Unhandled document download error: {"error": "Auth Error Of Some Kind"}'
|
||||
)
|
||||
|
||||
|
||||
def test_should_raise_exceptions_without_http_response_bodies_as_exceptions(document_download):
|
||||
with pytest.raises(expected_exception=Exception) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
def test_should_raise_exceptions_without_http_response_bodies_as_exceptions(
|
||||
document_download,
|
||||
):
|
||||
with pytest.raises(
|
||||
expected_exception=Exception
|
||||
) as excinfo, requests_mock.Mocker() as request_mock:
|
||||
request_mock.post(
|
||||
'https://document-download/services/service-id/documents',
|
||||
exc=requests.exceptions.ConnectTimeout
|
||||
"https://document-download/services/service-id/documents",
|
||||
exc=requests.exceptions.ConnectTimeout,
|
||||
)
|
||||
|
||||
document_download.upload_document('service-id', 'abababab')
|
||||
document_download.upload_document("service-id", "abababab")
|
||||
|
||||
assert type(excinfo.value) == Exception # make sure it's a base exception, so will be handled as a 500 by v2 api
|
||||
assert str(excinfo.value) == 'Unhandled document download error: ConnectTimeout()'
|
||||
assert (
|
||||
type(excinfo.value) == Exception
|
||||
) # make sure it's a base exception, so will be handled as a 500 by v2 api
|
||||
assert str(excinfo.value) == "Unhandled document download error: ConnectTimeout()"
|
||||
|
||||
@@ -7,61 +7,79 @@ from app.clients.performance_platform.performance_platform_client import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
@pytest.fixture(scope="function")
|
||||
def perf_client(client, mocker):
|
||||
perf_client = PerformancePlatformClient()
|
||||
current_app = mocker.Mock(config={
|
||||
'PERFORMANCE_PLATFORM_ENABLED': True,
|
||||
'PERFORMANCE_PLATFORM_ENDPOINTS': {
|
||||
'foo': 'my_token',
|
||||
'bar': 'other_token'
|
||||
},
|
||||
'PERFORMANCE_PLATFORM_URL': 'https://performance-platform-url/'
|
||||
})
|
||||
current_app = mocker.Mock(
|
||||
config={
|
||||
"PERFORMANCE_PLATFORM_ENABLED": True,
|
||||
"PERFORMANCE_PLATFORM_ENDPOINTS": {"foo": "my_token", "bar": "other_token"},
|
||||
"PERFORMANCE_PLATFORM_URL": "https://performance-platform-url/",
|
||||
}
|
||||
)
|
||||
perf_client.init_app(current_app)
|
||||
return perf_client
|
||||
|
||||
|
||||
def test_should_not_call_if_not_enabled(perf_client):
|
||||
with requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://performance-platform-url/foo', json={}, status_code=200)
|
||||
request_mock.post(
|
||||
"https://performance-platform-url/foo", json={}, status_code=200
|
||||
)
|
||||
perf_client._active = False
|
||||
perf_client.send_stats_to_performance_platform({'dataType': 'foo'})
|
||||
perf_client.send_stats_to_performance_platform({"dataType": "foo"})
|
||||
|
||||
assert request_mock.called is False
|
||||
|
||||
|
||||
def test_should_call_datatype_endpoint_if_enabled(perf_client):
|
||||
with requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://performance-platform-url/foo', json={}, status_code=200)
|
||||
perf_client.send_stats_to_performance_platform({'dataType': 'foo'})
|
||||
request_mock.post(
|
||||
"https://performance-platform-url/foo", json={}, status_code=200
|
||||
)
|
||||
perf_client.send_stats_to_performance_platform({"dataType": "foo"})
|
||||
|
||||
assert request_mock.call_count == 1
|
||||
assert request_mock.last_request.method == 'POST'
|
||||
assert request_mock.last_request.method == "POST"
|
||||
|
||||
|
||||
@pytest.mark.parametrize('dataset, token', [
|
||||
('foo', 'my_token'),
|
||||
('bar', 'other_token')
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"dataset, token", [("foo", "my_token"), ("bar", "other_token")]
|
||||
)
|
||||
def test_should_use_correct_token(perf_client, dataset, token):
|
||||
with requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://performance-platform-url/foo', json={}, status_code=200)
|
||||
request_mock.post('https://performance-platform-url/bar', json={}, status_code=200)
|
||||
perf_client.send_stats_to_performance_platform({'dataType': dataset})
|
||||
request_mock.post(
|
||||
"https://performance-platform-url/foo", json={}, status_code=200
|
||||
)
|
||||
request_mock.post(
|
||||
"https://performance-platform-url/bar", json={}, status_code=200
|
||||
)
|
||||
perf_client.send_stats_to_performance_platform({"dataType": dataset})
|
||||
|
||||
assert request_mock.call_count == 1
|
||||
assert request_mock.last_request.headers.get('authorization') == 'Bearer {}'.format(token)
|
||||
assert request_mock.last_request.headers.get("authorization") == "Bearer {}".format(
|
||||
token
|
||||
)
|
||||
|
||||
|
||||
def test_should_raise_for_status(perf_client):
|
||||
with pytest.raises(requests.HTTPError), requests_mock.Mocker() as request_mock:
|
||||
request_mock.post('https://performance-platform-url/foo', json={}, status_code=403)
|
||||
perf_client.send_stats_to_performance_platform({'dataType': 'foo'})
|
||||
request_mock.post(
|
||||
"https://performance-platform-url/foo", json={}, status_code=403
|
||||
)
|
||||
perf_client.send_stats_to_performance_platform({"dataType": "foo"})
|
||||
|
||||
|
||||
def test_generate_payload_id():
|
||||
payload = {'_timestamp': '2023-01-01 00:00:00', 'service': 'my_service', 'group_name': 'group_name',
|
||||
'dataType': 'dataType', 'period': 'period'}
|
||||
payload = {
|
||||
"_timestamp": "2023-01-01 00:00:00",
|
||||
"service": "my_service",
|
||||
"group_name": "group_name",
|
||||
"dataType": "dataType",
|
||||
"period": "period",
|
||||
}
|
||||
result = PerformancePlatformClient.generate_payload_id(payload, "group_name")
|
||||
assert result == 'MjAyMy0wMS0wMSAwMDowMDowMG15X3NlcnZpY2Vncm91cF9uYW1lZGF0YVR5cGVwZXJpb2Q='
|
||||
assert (
|
||||
result
|
||||
== "MjAyMy0wMS0wMSAwMDowMDowMG15X3NlcnZpY2Vncm91cF9uYW1lZGF0YVR5cGVwZXJpb2Q="
|
||||
)
|
||||
|
||||
@@ -8,7 +8,7 @@ def fake_client(notify_api):
|
||||
class FakeSmsClient(SmsClient):
|
||||
@property
|
||||
def name(self):
|
||||
return 'fake'
|
||||
return "fake"
|
||||
|
||||
fake_client = FakeSmsClient()
|
||||
# fake_client.init_app(notify_api)
|
||||
@@ -16,31 +16,35 @@ def fake_client(notify_api):
|
||||
|
||||
|
||||
def test_send_sms(fake_client, mocker):
|
||||
mock_send = mocker.patch.object(fake_client, 'send_sms')
|
||||
mock_send = mocker.patch.object(fake_client, "send_sms")
|
||||
|
||||
fake_client.send_sms(
|
||||
to='to',
|
||||
content='content',
|
||||
reference='reference',
|
||||
to="to",
|
||||
content="content",
|
||||
reference="reference",
|
||||
international=False,
|
||||
sender='testing',
|
||||
sender="testing",
|
||||
)
|
||||
|
||||
mock_send.assert_called_with(
|
||||
to='to', content='content', reference='reference', international=False, sender='testing'
|
||||
to="to",
|
||||
content="content",
|
||||
reference="reference",
|
||||
international=False,
|
||||
sender="testing",
|
||||
)
|
||||
|
||||
|
||||
def test_send_sms_error(fake_client, mocker):
|
||||
mocker.patch.object(
|
||||
fake_client, 'send_sms', side_effect=SmsClientResponseException('error')
|
||||
fake_client, "send_sms", side_effect=SmsClientResponseException("error")
|
||||
)
|
||||
|
||||
with pytest.raises(SmsClientResponseException):
|
||||
fake_client.send_sms(
|
||||
to='to',
|
||||
content='content',
|
||||
reference='reference',
|
||||
to="to",
|
||||
content="content",
|
||||
reference="reference",
|
||||
international=False,
|
||||
sender=None,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user