more tests

This commit is contained in:
Kenneth Kehl
2023-08-14 15:32:22 -07:00
parent b4a2f37ca9
commit b9ba7d018b
10 changed files with 109 additions and 0 deletions

View File

@@ -336,6 +336,7 @@ def create_random_identifier():
return ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16)) return ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16))
# TODO maintainability what is the purpose of this? Debugging?
def setup_sqlalchemy_events(app): def setup_sqlalchemy_events(app):
TOTAL_DB_CONNECTIONS = Gauge( TOTAL_DB_CONNECTIONS = Gauge(

View File

@@ -147,6 +147,8 @@ def purge_functional_test_data(user_email_prefix):
@click.option('-f', '--file_name', required=True, @click.option('-f', '--file_name', required=True,
help="""Full path of the file to upload, file is a contains inbound numbers, one number per line.""") help="""Full path of the file to upload, file is a contains inbound numbers, one number per line.""")
def insert_inbound_numbers_from_file(file_name): def insert_inbound_numbers_from_file(file_name):
# TODO maintainability what is the purpose of this command? Who would use it and why?
print("Inserting inbound numbers from {}".format(file_name)) print("Inserting inbound numbers from {}".format(file_name))
with open(file_name) as file: with open(file_name) as file:
sql = "insert into inbound_numbers values('{}', '{}', 'sns', null, True, now(), null);" sql = "insert into inbound_numbers values('{}', '{}', 'sns', null, True, now(), null);"
@@ -168,6 +170,9 @@ def setup_commands(application):
@click.option('-d', '--day', help="The date to recalculate, as YYYY-MM-DD", required=True, @click.option('-d', '--day', help="The date to recalculate, as YYYY-MM-DD", required=True,
type=click_dt(format='%Y-%m-%d')) type=click_dt(format='%Y-%m-%d'))
def rebuild_ft_billing_for_day(service_id, day): def rebuild_ft_billing_for_day(service_id, day):
# TODO maintainability what is the purpose of this command? Who would use it and why?
""" """
Rebuild the data in ft_billing for the given service_id and date Rebuild the data in ft_billing for the given service_id and date
""" """
@@ -386,6 +391,8 @@ def populate_service_volume_intentions(file_name):
# [1] SMS:: volume intentions for service # [1] SMS:: volume intentions for service
# [2] Email:: volume intentions for service # [2] Email:: volume intentions for service
# TODO maintainability what is the purpose of this command? Who would use it and why?
with open(file_name, 'r') as f: with open(file_name, 'r') as f:
for line in itertools.islice(f, 1, None): for line in itertools.islice(f, 1, None):
columns = line.split(',') columns = line.split(',')

View File

@@ -45,6 +45,7 @@ class InvalidRequest(Exception):
return str(self.to_dict()) return str(self.to_dict())
# TODO maintainability what is this for? How to unit test it?
def register_errors(blueprint): def register_errors(blueprint):
@blueprint.errorhandler(InvalidEmailError) @blueprint.errorhandler(InvalidEmailError)
def invalid_format(error): def invalid_format(error):

View File

@@ -1,3 +1,4 @@
from app.dao import DAOClass
from app.dao.permissions_dao import permission_dao from app.dao.permissions_dao import permission_dao
from tests.app.db import create_service from tests.app.db import create_service
@@ -22,3 +23,17 @@ def test_get_permissions_by_user_id_returns_only_active_service(sample_user):
assert len(permissions) == 7 assert len(permissions) == 7
assert active_service in [i.service for i in permissions] assert active_service in [i.service for i in permissions]
assert inactive_service not in [i.service for i in permissions] assert inactive_service not in [i.service for i in permissions]
def test_dao_class(sample_user):
create_service(user=sample_user, service_name="Active service")
create_service(user=sample_user, service_name="Inactive service", active=False)
permissions_orig = permission_dao.get_permissions_by_user_id(user_id=sample_user.id)
assert len(permissions_orig) == 7
dao = DAOClass()
for permission in permissions_orig:
dao.delete_instance(permission, True)
permissions = permission_dao.get_permissions_by_user_id(user_id=sample_user.id)
assert len(permissions) == 0

View File

@@ -12,6 +12,7 @@ from app.dao.service_user_dao import (
dao_update_service_user, dao_update_service_user,
) )
from app.dao.users_dao import ( from app.dao.users_dao import (
_remove_values_for_keys_if_present,
count_user_verify_codes, count_user_verify_codes,
create_secret_code, create_secret_code,
dao_archive_user, dao_archive_user,
@@ -294,3 +295,16 @@ def test_user_cannot_be_archived_if_the_other_service_members_do_not_have_the_ma
assert len(sample_service.users) == 3 assert len(sample_service.users) == 3
assert not user_can_be_archived(active_user) assert not user_can_be_archived(active_user)
def test_remove_values_for_keys_if_present():
keys = {'a', 'b', 'c'}
my_dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
}
_remove_values_for_keys_if_present(my_dict, keys)
assert my_dict == {'d': 4}

View File

@@ -1,5 +1,6 @@
from base64 import b64encode from base64 import b64encode
from datetime import datetime from datetime import datetime
from unittest import mock
import pytest import pytest
from flask import json from flask import json
@@ -7,6 +8,7 @@ from flask import json
from app.models import EMAIL_TYPE, INBOUND_SMS_TYPE, SMS_TYPE, InboundSms from app.models import EMAIL_TYPE, INBOUND_SMS_TYPE, SMS_TYPE, InboundSms
from app.notifications.receive_notifications import ( from app.notifications.receive_notifications import (
create_inbound_sms_object, create_inbound_sms_object,
fetch_potential_service,
has_inbound_sms_permissions, has_inbound_sms_permissions,
unescape_string, unescape_string,
) )
@@ -290,3 +292,15 @@ def test_create_inbound_sms_object_works_with_alphanumeric_sender(sample_service
) )
assert inbound_sms.user_number == 'ALPHANUM3R1C' assert inbound_sms.user_number == 'ALPHANUM3R1C'
@mock.patch('app.notifications.receive_notifications.dao_fetch_service_by_inbound_number')
def test_fetch_potential_service_cant_find_it(mock_dao):
mock_dao.return_value = None
found_service = fetch_potential_service(234, 'sns')
assert found_service is False
# Permissions will not be set so it will still return false
mock_dao.return_value = create_service()
found_service = fetch_potential_service(234, 'sns')
assert found_service is False

View File

@@ -9,6 +9,11 @@ from app.models import EMAIL_TYPE, SMS_TYPE
from app.notifications.process_notifications import ( from app.notifications.process_notifications import (
create_content_for_notification, create_content_for_notification,
) )
from app.notifications.sns_cert_validator import (
VALID_SNS_TOPICS,
get_string_to_sign,
validate_sns_cert,
)
from app.notifications.validators import ( from app.notifications.validators import (
check_application_over_retention_limit, check_application_over_retention_limit,
check_if_service_can_send_files_by_email, check_if_service_can_send_files_by_email,
@@ -535,3 +540,34 @@ def test_check_if_service_can_send_files_by_email_passes_if_contact_link_set(sam
service_contact_link=sample_service.contact_link, service_contact_link=sample_service.contact_link,
service_id=sample_service.id service_id=sample_service.id
) )
def test_get_string_to_sign():
VALID_SNS_TOPICS.append("arn:aws:sns:us-west-2:009969138378:connector-svc-test")
sns_payload = {
"Type": "Notification",
"MessageId": "ccccccccc-cccc-cccc-cccc-ccccccccccccc",
"TopicArn": "arn:aws:sns:us-west-2:009969138378:connector-svc-test",
"Message": "{\"AbsoluteTime\":\"2021-09-08T13:28:24.656Z\",\"Content\":\"help\",\"ContentType\":\"text/plain\",\"Id\":\"333333333-be0d-4a44-889d-d2a86fc06f0c\",\"Type\":\"MESSAGE\",\"ParticipantId\":\"bbbbbbbb-c562-4d95-b76c-dcbca8b4b5f7\",\"DisplayName\":\"Jane\",\"ParticipantRole\":\"CUSTOMER\",\"InitialContactId\":\"33333333-abc5-46db-9ad5-d772559ab556\",\"ContactId\":\"33333333-abc5-46db-9ad5-d772559ab556\"}", # noqa
"Timestamp": "2021-09-08T13:28:24.860Z",
"SignatureVersion": "1",
"Signature": "examplegggggg/1tEBYdiVDgJgBoJUniUFcArLFGfg5JCvpOr/v6LPCHiD7A0BWy8+ZOnGTmOjBMn80U9jSzYhKbHDbQHaNYTo9sRyQA31JtHHiIseQeMfTDpcaAXqfs8hdIXq4XZaJYqDFqosfbvh56VPh5QgmeHTltTc7eOZBUwnt/177eOTLTt2yB0ItMV3NAYuE1Tdxya1lLYZQUIMxETTVcRAZkDIu8TbRZC9a00q2RQVjXhDaU3k+tL+kk85syW/2ryjjkDYoUb+dyRGkqMy4aKA22UpfidOtdAZ/GGtXaXSKBqazZTEUuSEzt0duLtFntQiYJanU05gtDig==", # noqa
"SigningCertURL": "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-11111111111111111111111111111111.pem", # noqa
"UnsubscribeURL": "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:000000000000:connector-svc-test:22222222-aaaa-bbbb-cccc-333333333333", # noqa
"MessageAttributes": {
"InitialContactId": {"Type": "String", "Value": "33333333-abc5-46db-9ad5-d772559ab556"},
"MessageVisibility": {"Type": "String", "Value": "ALL"},
"Type": {"Type": "String", "Value": "MESSAGE"},
"AccountId": {"Type": "String", "Value": "999999999999"},
"ContentType": {"Type": "String", "Value": "text/plain"},
"InstanceId": {"Type": "String", "Value": "dddddddd-b64e-40c5-921b-109fd92499ae"},
"ContactId": {"Type": "String", "Value": "33333333-abc5-46db-9ad5-d772559ab556"},
"ParticipantRole": {"Type": "String", "Value": "CUSTOMER"}
}
}
str = get_string_to_sign(sns_payload)
assert str == b'Message\n{"AbsoluteTime":"2021-09-08T13:28:24.656Z","Content":"help","ContentType":"text/plain","Id":"333333333-be0d-4a44-889d-d2a86fc06f0c","Type":"MESSAGE","ParticipantId":"bbbbbbbb-c562-4d95-b76c-dcbca8b4b5f7","DisplayName":"Jane","ParticipantRole":"CUSTOMER","InitialContactId":"33333333-abc5-46db-9ad5-d772559ab556","ContactId":"33333333-abc5-46db-9ad5-d772559ab556"}\nMessageId\nccccccccc-cccc-cccc-cccc-ccccccccccccc\nTimestamp\n2021-09-08T13:28:24.860Z\nTopicArn\narn:aws:sns:us-west-2:009969138378:connector-svc-test\nType\nNotification\n' # noqa
# This is a test payload with no valid cert, so it should raise a ValueError
with pytest.raises(ValueError):
validate_sns_cert(sns_payload)

6
tests/app/test_errors.py Normal file
View File

@@ -0,0 +1,6 @@
from app.errors import VirusScanError
def test_virus_scan_error():
vse = VirusScanError("a message")
assert "a message" in vse.args

View File

@@ -0,0 +1,6 @@
from app.exceptions import DVLAException
def test_dvla_exception():
dvla = DVLAException("a message")
assert dvla.message == "a message"

View File

@@ -1,3 +1,4 @@
import json
import uuid import uuid
from datetime import datetime from datetime import datetime
from unittest import mock from unittest import mock
@@ -47,6 +48,14 @@ def test_get_user_list(admin_request, sample_service):
assert sorted(expected_permissions) == sorted(fetched['permissions'][str(sample_service.id)]) assert sorted(expected_permissions) == sorted(fetched['permissions'][str(sample_service.id)])
def test_get_all_users(admin_request):
create_user()
json_resp = admin_request.get('user.get_all_users')
json_resp_str = json.dumps(json_resp)
assert 'Test User' in json_resp_str
assert '+12028675309' in json_resp_str
def test_get_user(admin_request, sample_service, sample_organization): def test_get_user(admin_request, sample_service, sample_organization):
""" """
Tests GET endpoint '/<user_id>' to retrieve a single service. Tests GET endpoint '/<user_id>' to retrieve a single service.