Skip to content

Home Information - Your home, your data, organized.

Python

Fixed unit test setup issues.

Anthony Cassandra8feda6a7a662
diff --git a/docs/dev/Guidelines.md b/docs/dev/Guidelines.md
index a74a6e19..81c3a4c4 100644
--- a/docs/dev/Guidelines.md
+++ b/docs/dev/Guidelines.md
@@ -43,6 +43,7 @@
- `monitors.py`: If app module needs a periodic background process.
- `templates/${APPNAME}`: The apps templates. Also see the [Templates Page](Templates.md).
- `apps.py`: Django-required module definition.
+- `tests/test_${NAME}`: Unit tests for the module (by Django conventions).
- `admin.py`: For adding to Django admin console (by Django conventions).
If a module provides views or functionality that is only applicable to edit mode, then an `edit` subdirectory is used with the same structure, e.g.,
diff --git a/src/hi/apps/__init__.py b/src/hi/apps/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/common/jwt_token_manager.py b/src/hi/apps/common/jwt_token_manager.py
deleted file mode 100644
index 6a66a7a3..00000000
--- a/src/hi/apps/common/jwt_token_manager.py
+++ /dev/null
@@ -1,134 +0,0 @@
-import jwt
-import time
-
-from cachetools import TTLCache
-
-from waa.apps.common.enums import LabeledEnum
-from waa.apps.common.singleton import Singleton
-
-
-class JwtTokenError(Exception):
- pass
-
-
-class JwtTokenAlgorithm(LabeledEnum):
-
- ES256 = (
- 'ES256',
- 'Elliptic Curve Digital Signature Algorithm with the P-256 curve and the SHA-256 hash function.',
- 'ES256',
- 'ES256',
- )
- HS256 = (
- 'HS256',
- 'HMAC using SHA-256',
- 'HS256',
- 'HS256',
- )
-
- def __init__( self,
- label : str,
- description : str,
- header_name : str,
- encoding_name : str ):
- super().__init__( label, description )
- self.header_name = header_name
- self.encoding_name = encoding_name
- return
-
-
-class JwtTokenManager( Singleton ):
-
- TOKEN_CACHE_EXPIRY_SECS = 15 * 60 # Max is 20 min for Apple Connect Store API
-
- def __init_singleton__( self ):
- self._token_cache = TTLCache( maxsize = 4, ttl = self.TOKEN_CACHE_EXPIRY_SECS )
- return
-
- def get_token( self,
- issuer_id : str,
- key_id : str,
- private_key : str,
- audience : str,
- algorithm : JwtTokenAlgorithm,
- bundle_id : str = None,
- token_expiration_secs : int = 900 ):
- """ Uses cache version for creating token """
-
- assert token_expiration_secs <= ( 20 * 60 ) # Max expiration time (20 minutes for Apple API)
-
- cache_key = f'{issuer_id}:{key_id}:{audience}:{algorithm}'
- if cache_key in self._token_cache:
- return self._token_cache[cache_key]
-
- jwt_token = self.create_token(
- issuer_id = issuer_id,
- key_id = key_id,
- private_key = private_key,
- audience = audience,
- algorithm = algorithm,
- bundle_id = bundle_id,
- token_expiration_secs = token_expiration_secs,
- )
- self._token_cache[cache_key] = jwt_token
- return jwt_token
-
- def create_token( self,
- issuer_id : str,
- key_id : str,
- private_key : str,
- audience : str,
- algorithm : JwtTokenAlgorithm,
- bundle_id : str = None,
- token_expiration_secs : int = 900 ):
- """ Non-cache version for creating token """
-
- assert token_expiration_secs <= ( 20 * 60 ) # Max expiration time (20 minutes for Apple API)
-
- if not issuer_id or not isinstance( issuer_id, str ) or issuer_id.isspace():
- raise JwtTokenError( 'Missing issuer id or wrong type.' )
- if not key_id or not isinstance( key_id, str ) or key_id.isspace():
- raise JwtTokenError( 'Missing key id or wrong type.' )
- if not private_key or not isinstance( private_key, str ) or private_key.isspace():
- raise JwtTokenError( 'Missing private key or wronmg type.' )
- if not audience or not isinstance( audience, str ) or audience.isspace():
- raise JwtTokenError( 'Missing audience or wrong type.' )
- if not algorithm or not isinstance( algorithm, JwtTokenAlgorithm ):
- raise JwtTokenError( 'Missing algorithm or wrong type.' )
-
- current_time_epoch_secs = self.get_current_time_epoch_secs()
-
- headers = {
- "alg": algorithm.header_name,
- "kid": key_id,
- "typ": "JWT",
- }
- payload = {
- "iss": issuer_id,
- 'iat': current_time_epoch_secs,
- "exp": current_time_epoch_secs + token_expiration_secs,
- "aud": audience,
- }
- if bundle_id:
- payload['bid'] = bundle_id
-
- try:
- jwt_token = jwt.encode(
- payload,
- private_key,
- algorithm = algorithm.encoding_name,
- headers = headers,
- )
- return jwt_token
- except ValueError as ve:
- raise JwtTokenError( str(ve) )
-
- def get_current_time_epoch_secs(self):
- # Allows mocking for unit tests
- return int( time.time() )
-
- def clear_cache( self ):
- self._token_cache.clear()
- return
-
-
diff --git a/src/hi/apps/common/tests.py b/src/hi/apps/common/tests.py
deleted file mode 100644
index 7ce503c2..00000000
--- a/src/hi/apps/common/tests.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from django.test import TestCase
-
-# Create your tests here.
diff --git a/src/hi/apps/common/tests/test_datetimeproxy.py b/src/hi/apps/common/tests/test_datetimeproxy.py
index d32044e0..ebcef7e4 100644
--- a/src/hi/apps/common/tests/test_datetimeproxy.py
+++ b/src/hi/apps/common/tests/test_datetimeproxy.py
@@ -5,7 +5,7 @@ import unittest
from django.utils import timezone
-import waa.apps.common.datetimeproxy as datetimeproxy
+import hi.apps.common.datetimeproxy as datetimeproxy
logging.disable(logging.CRITICAL)
diff --git a/src/hi/apps/common/tests/test_email_utils.py b/src/hi/apps/common/tests/test_email_utils.py
index 3367ba6b..7ff31149 100644
--- a/src/hi/apps/common/tests/test_email_utils.py
+++ b/src/hi/apps/common/tests/test_email_utils.py
@@ -2,7 +2,7 @@ import logging
from django.test import TestCase
-import waa.apps.common.email_utils as email_utils
+import hi.apps.common.email_utils as email_utils
logging.disable(logging.CRITICAL)
diff --git a/src/hi/apps/common/tests/test_jwt_token_manager.py b/src/hi/apps/common/tests/test_jwt_token_manager.py
deleted file mode 100644
index a2f64865..00000000
--- a/src/hi/apps/common/tests/test_jwt_token_manager.py
+++ /dev/null
@@ -1,275 +0,0 @@
-import base64
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.backends import default_backend
-import json
-import jwt
-import logging
-from unittest.mock import patch
-import time
-
-from django.test import TestCase
-
-from waa.apps.common.jwt_token_manager import (
- JwtTokenError,
- JwtTokenAlgorithm,
- JwtTokenManager,
-)
-
-logging.disable(logging.CRITICAL)
-
-
-class JwtTokenManagerTestCase(TestCase):
-
- def setUp(self):
- # Test keys generated with:
- #
- # openssl ecparam -genkey -name prime256v1 -noout -out ec_private_key.pem
-
- self.TEST_PRIVATE_KEY_1 = """-----BEGIN EC PRIVATE KEY-----
-MHcCAQEEIEK/C1jPHfxm5lXj+tDt/P/EJFnp2xXsbeRc2urem2dRoAoGCCqGSM49
-AwEHoUQDQgAEnLbLcrnQ07e4vc79TqD8D3APe+Bw/QTGl/RFC4SaZNYQuZnL0V5a
-BrLFpdU80BGZg4RlrExqAzEtkgS0V8CBMw==
------END EC PRIVATE KEY-----"""
-
- return
-
- def test_create_token__bad_issuer_id(self):
-
- manager = JwtTokenManager()
-
- for issuer_id in [ None, '', ' ' ]:
- with self.assertRaises( JwtTokenError ):
- manager.create_token(
- issuer_id = issuer_id,
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- continue
- return
-
- def test_create_token__bad_key_id(self):
-
- manager = JwtTokenManager()
-
- for key_id in [ None, '', ' ' ]:
- with self.assertRaises( JwtTokenError ):
- manager.create_token(
- issuer_id = 'test_issuer',
- key_id = key_id,
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- continue
- return
-
- def test_create_token__bad_private_key(self):
-
- manager = JwtTokenManager()
-
- for private_key in [ None, '', ' ', 'bogus' ]:
- with self.assertRaises( JwtTokenError ):
- manager.create_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = private_key,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- continue
- return
-
- def test_create_token__bad_audience(self):
-
- manager = JwtTokenManager()
-
- for audience in [ None, '', ' ' ]:
- with self.assertRaises( JwtTokenError ):
- manager.create_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = audience,
- algorithm = JwtTokenAlgorithm.ES256,
- )
- continue
- return
-
- def test_create_token__bad_algorithm(self):
-
- manager = JwtTokenManager()
-
- for algorithm in [ None, '', ' ' ]:
- with self.assertRaises( JwtTokenError ):
- manager.create_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = algorithm,
- )
- continue
- return
-
-
- @patch.object(JwtTokenManager, 'get_current_time_epoch_secs')
- def test_create_token__happy_path( self, mock_get_current_time ):
- current_time_epoch_secs = int(time.time())
- token_expiration_secs = 10 * 60
-
- mock_get_current_time.return_value = current_time_epoch_secs
-
- # Need a public key for verification check
- private_key = serialization.load_pem_private_key(
- self.TEST_PRIVATE_KEY_1.encode(),
- password = None,
- backend = default_backend()
- )
- public_key = private_key.public_key()
-
- expected_headers = {
- "alg": JwtTokenAlgorithm.ES256.header_name,
- "kid": 'test_key_id',
- "typ": "JWT",
- }
- expected_payload = {
- "iss": 'test_issuer_id',
- 'iat': current_time_epoch_secs,
- "exp": current_time_epoch_secs + token_expiration_secs,
- "aud": 'appstoreconnect-v1',
- "bid": 'com.pomdp.wordsacrossamerica',
- }
-
- manager = JwtTokenManager()
-
- jwt_token = manager.create_token(
- issuer_id = expected_payload['iss'],
- key_id = expected_headers['kid'],
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = expected_payload['aud'],
- algorithm = JwtTokenAlgorithm.ES256,
- bundle_id = expected_payload['bid'],
- token_expiration_secs = token_expiration_secs,
- )
-
- ( encoded_header, encoded_payload, signature ) = jwt_token.split( '.' )
-
- decoded_header = base64.b64decode( encoded_header + "===" ) # Needs padding for multiple of 4
- decoded_payload = base64.b64decode( encoded_payload + "===" ) # Needs padding for multiple of 4
-
- decoded_header_json = json.loads( decoded_header )
- decoded_payload_json = json.loads( decoded_payload )
-
- self.assertEqual( expected_headers, decoded_header_json )
- self.assertEqual( expected_payload, decoded_payload_json )
-
- try:
- _ = jwt.decode(
- jwt_token,
- public_key,
- algorithms = [ JwtTokenAlgorithm.ES256.encoding_name ],
- audience = expected_payload['aud'],
- )
- except Exception:
- self.fail("Token signature could not be decoded.")
-
- return
-
- @patch.object(JwtTokenManager, 'get_current_time_epoch_secs')
- def test_get_token__happy_path( self, mock_get_current_time ):
- mock_get_current_time.return_value = 1234567890
-
- manager = JwtTokenManager()
-
- ##########
- # First make sure that tokens with randomness in algorithm are not
- # the same via create_token().
-
- jwt_token_1 = manager.create_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- jwt_token_2 = manager.create_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertNotEqual( jwt_token_1, jwt_token_2 )
-
- ##########
- # Now make sure that consecutive calls to get_token() return from
- # cache, (cache key does not depend on private key).
-
- jwt_token_1 = manager.get_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- jwt_token_2 = manager.get_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertEqual( jwt_token_1, jwt_token_2 )
-
- ##########
- # Change of issuer id should bust the CACHE
-
- jwt_token_2 = manager.get_token(
- issuer_id = 'test_issuer_2',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertNotEqual( jwt_token_1, jwt_token_2 )
-
- ##########
- # Change of key id should bust the CACHE
-
- jwt_token_2 = manager.get_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id_2',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertNotEqual( jwt_token_1, jwt_token_2 )
-
- ##########
- # Change of audience should bust the CACHE
-
- jwt_token_2 = manager.get_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v2',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertNotEqual( jwt_token_1, jwt_token_2 )
-
- ##########
- # Double check original params still getting cached result.
-
- jwt_token_2 = manager.get_token(
- issuer_id = 'test_issuer',
- key_id = 'test_key_id',
- private_key = self.TEST_PRIVATE_KEY_1,
- audience = 'appstoreconnect-v1',
- algorithm = JwtTokenAlgorithm.ES256,
- )
- self.assertEqual( jwt_token_1, jwt_token_2 )
-
- return
-
diff --git a/src/hi/apps/common/tests/test_name_utils.py b/src/hi/apps/common/tests/test_name_utils.py
index 12abc747..41fe3ee8 100644
--- a/src/hi/apps/common/tests/test_name_utils.py
+++ b/src/hi/apps/common/tests/test_name_utils.py
@@ -2,7 +2,7 @@ import logging
from django.test import TestCase
-import waa.apps.common.name_utils as name_utils
+import hi.apps.common.name_utils as name_utils
logging.disable(logging.CRITICAL)
diff --git a/src/hi/apps/common/tests/test_pagination.py b/src/hi/apps/common/tests/test_pagination.py
index 05ef43ff..b377851e 100644
--- a/src/hi/apps/common/tests/test_pagination.py
+++ b/src/hi/apps/common/tests/test_pagination.py
@@ -2,7 +2,7 @@ import logging
from django.test import TestCase
-from waa.apps.common.pagination import compute_pagination
+from hi.apps.common.pagination import compute_pagination
logging.disable(logging.CRITICAL)
diff --git a/src/hi/apps/common/tests/test_url_utils.py b/src/hi/apps/common/tests/test_url_utils.py
index 1f8cc46e..5fd059f9 100644
--- a/src/hi/apps/common/tests/test_url_utils.py
+++ b/src/hi/apps/common/tests/test_url_utils.py
@@ -2,7 +2,7 @@ import logging
from django.test import TestCase
-from waa.apps.common.url_utils import simplify_url_path
+from hi.apps.common.url_utils import simplify_url_path
logging.disable(logging.CRITICAL)
diff --git a/src/hi/apps/common/tests/test_utils.py b/src/hi/apps/common/tests/test_utils.py
index afb29cef..032cfc6f 100644
--- a/src/hi/apps/common/tests/test_utils.py
+++ b/src/hi/apps/common/tests/test_utils.py
@@ -3,7 +3,7 @@ import logging
from django.contrib.auth import get_user_model
from django.test import TestCase
-import waa.apps.common.utils as utils
+import hi.apps.common.utils as utils
logging.disable(logging.CRITICAL)
@@ -239,16 +239,6 @@ class CommonUtilsTestCase(TestCase):
continue
return
- def test_hash_with_seed(self):
-
- # This guards against changing the seed value. Do not change the seed value.
-
- self.assertEqual( '2e6451b4d14aded1fba1d30dcc780a04265238a4fa4813c1e69bc931344cd3b6',
- utils.hash_with_seed( value = None ) )
- self.assertEqual( 'e8a59d67adb70cccff3b36bb5a079d5b2519e4013ec3d02548446a099a66d7a1',
- utils.hash_with_seed( value = '[email protected]' ) )
- return
-
def test_get_url_top_level_domain(self):
data_list = [