The great bump

This commit is contained in:
2021-08-06 16:29:01 +00:00
parent f764b73f66
commit 0672a17d2e
195 changed files with 5791 additions and 4983 deletions

169
apps/cic-ussd/tests/fixtures/account.py vendored Normal file
View File

@@ -0,0 +1,169 @@
# standard imports
import json
import random
# external accounts
import pytest
from chainlib.hash import strip_0x
# local imports
from cic_ussd.account.chain import Chain
from cic_ussd.cache import cache_data, cache_data_key
from cic_ussd.db.enum import AccountStatus
from cic_ussd.db.models.account import Account
# test imports
from tests.helpers.accounts import blockchain_address, phone_number
@pytest.fixture(scope='function')
def account_creation_data(task_uuid):
return {
'phone_number': phone_number(),
'sms_notification_sent': False,
'status': 'PENDING',
'task_uuid': task_uuid
}
@pytest.fixture(scope='function')
def activated_account(init_database, set_fernet_key):
account = Account(blockchain_address(), phone_number())
account.create_password('0000')
account.activate_account()
init_database.add(account)
init_database.commit()
return account
@pytest.fixture(scope='function')
def balances():
return [{
'address': blockchain_address(),
'converters': [],
'balance_network': 50000000,
'balance_outgoing': 0,
'balance_incoming': 0
}]
@pytest.fixture(scope='function')
def cache_account_creation_data(init_cache, account_creation_data):
cache_data(account_creation_data.get('task_uuid'), json.dumps(account_creation_data))
@pytest.fixture(scope='function')
def cache_balances(activated_account, balances, init_cache):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
balances = json.dumps(balances[0])
key = cache_data_key(identifier, ':cic.balances')
cache_data(key, balances)
@pytest.fixture(scope='function')
def cache_default_token_data(default_token_data, init_cache, load_chain_spec):
chain_str = Chain.spec.__str__()
data = json.dumps(default_token_data)
key = cache_data_key(chain_str.encode('utf-8'), ':cic.default_token_data')
cache_data(key, data)
@pytest.fixture(scope='function')
def cache_person_metadata(activated_account, init_cache, person_metadata):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
person = json.dumps(person_metadata)
key = cache_data_key(identifier, ':cic.person')
cache_data(key, person)
@pytest.fixture(scope='function')
def cache_preferences(activated_account, init_cache, preferences):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
preferences = json.dumps(preferences)
key = cache_data_key(identifier, ':cic.preferences')
cache_data(key, preferences)
@pytest.fixture(scope='function')
def cache_statement(activated_account, init_cache, statement):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
preferences = json.dumps(statement)
key = cache_data_key(identifier, ':cic.statement')
cache_data(key, preferences)
@pytest.fixture(scope='function')
def custom_metadata():
return {"tags": ["ussd", "individual"]}
@pytest.fixture(scope='function')
def default_token_data(token_symbol):
return {
'symbol': token_symbol,
'address': blockchain_address(),
'name': 'Giftable',
'decimals': 6
}
@pytest.fixture(scope='function')
def locked_accounts_traffic(init_database, set_fernet_key):
for _ in range(20):
address = blockchain_address()
phone = phone_number()
account = Account(address, phone)
account.create_password(str(random.randint(1000, 9999)))
account.failed_pin_attempts = 3
account.status = AccountStatus.LOCKED.value
init_database.add(account)
init_database.commit()
@pytest.fixture(scope='function')
def pending_account(init_database, set_fernet_key):
account = Account(blockchain_address(), phone_number())
init_database.add(account)
init_database.commit()
return account
@pytest.fixture(scope='function')
def pin_blocked_account(init_database, set_fernet_key):
account = Account(blockchain_address(), phone_number())
account.create_password('3333')
account.failed_pin_attempts = 3
init_database.add(account)
init_database.commit()
return account
@pytest.fixture(scope='function')
def preferences():
return {
'preferred_language': random.sample(['en', 'sw'], 1)[0]
}
@pytest.fixture(scope='function')
def raw_person_metadata():
return {
"date_of_birth": {
'year': 1998
},
"family_name": "Snow",
"given_name": "Name",
"gender": 'Male',
"location": "Kangemi",
"products": "Mandazi"
}
@pytest.fixture(scope='function')
def valid_recipient(init_database, set_fernet_key):
account = Account(blockchain_address(), phone_number())
account.create_password('2222')
account.activate_account()
init_database.add(account)
init_database.commit()
return account

15
apps/cic-ussd/tests/fixtures/cache.py vendored Normal file
View File

@@ -0,0 +1,15 @@
# standard imports
# external imports
import pytest
# local imports
from cic_ussd.cache import Cache
from cic_ussd.session.ussd_session import UssdSession
@pytest.fixture(scope='function')
def init_cache(redisdb):
Cache.store = redisdb
UssdSession.store = redisdb
return redisdb

View File

@@ -1,115 +0,0 @@
# standard imports
import json
# third party imports
import pytest
# local imports
from cic_ussd.redis import InMemoryStore
@pytest.fixture(scope='function')
def account_creation_action_data():
return {
'phone_number': '+254712345678',
'sms_notification_sent': False,
'status': 'PENDING',
'task_id': '31e85315-feee-4b6d-995e-223569082cc4'
}
@pytest.fixture(scope='function')
def set_account_creation_action_data(init_redis_cache, account_creation_action_data):
redis_cache = init_redis_cache
action_data = account_creation_action_data
task_id = action_data.get('task_id')
redis_cache.set(task_id, json.dumps(action_data))
redis_cache.persist(task_id)
@pytest.fixture(scope='function')
def successful_incoming_token_gift_callback():
return {
'RESULT': {
'hash': '0xb469fb2ebacc9574afb7b51d44e174fba7129fde71bf757fd39784363270832b',
'sender': '0xd6204101012270Bf2558EDcFEd595938d1847bf0',
'recipient': '0xFD9c5aD15C72C6F60f1a119A608931226674243f',
'source_value': 1048576,
'destination_value': 1048576,
'source_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'destination_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'source_token_symbol': 'SRF',
'destination_token_symbol': 'SRF',
'source_token_decimals': 18,
'destination_token_decimals': 18,
'chain': 'Bloxberg:8996'
},
'PARAM': 'tokengift',
'STATUS_CODE': 0,
}
@pytest.fixture(scope='function')
def successful_incoming_transfer_callback():
return {
'RESULT': {
'hash': '0x8b0ed32533164d010afc46c0011fbcb58b0198e03c05b96e2791555746bd3606',
'sender': '0xd6204101012270Bf2558EDcFEd595938d1847bf1',
'recipient': '0xd6204101012270Bf2558EDcFEd595938d1847bf0',
'source_value': 10000000000000000000000,
'destination_value': 10000000000000000000000,
'source_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'destination_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'source_token_symbol': 'SRF',
'destination_token_symbol': 'SRF',
'source_token_decimals': 18,
'destination_token_decimals': 18,
'chain': 'Bloxberg:8996'
},
'PARAM': 'transfer',
'STATUS_CODE': 0
}
@pytest.fixture(scope='function')
def incoming_transfer_callback_invalid_tx_status_code():
return {
'RESULT': {
'hash': '0x8b0ed32533164d010afc46c0011fbcb58b0198e03c05b96e2791555746bd3606',
'sender': '0xd6204101012270Bf2558EDcFEd595938d1847bf1',
'recipient': '0xd6204101012270Bf2558EDcFEd595938d1847bf0',
'source_value': 10000000000000000000000,
'destination_value': 10000000000000000000000,
'source_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'destination_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'source_token_symbol': 'SRF',
'destination_token_symbol': 'SRF',
'source_token_decimals': 18,
'destination_token_decimals': 18,
'chain': 'Bloxberg:8996'
},
'PARAM': 'transfer',
'STATUS_CODE': 1
}
@pytest.fixture(scope='function')
def incoming_transfer_callback_invalid_tx_param():
return {
'RESULT': {
'hash': '0x8b0ed32533164d010afc46c0011fbcb58b0198e03c05b96e2791555746bd3606',
'sender': '0xd6204101012270Bf2558EDcFEd595938d1847bf1',
'recipient': '0xd6204101012270Bf2558EDcFEd595938d1847bf0',
'source_value': 10000000000000000000000,
'destination_value': 10000000000000000000000,
'source_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'destination_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'source_token_symbol': 'SRF',
'destination_token_symbol': 'SRF',
'source_token_decimals': 18,
'destination_token_decimals': 18,
'chain': 'Bloxberg:8996'
},
'PARAM': 'erroneousparam',
'STATUS_CODE': 0
}

View File

@@ -1,42 +1,28 @@
# standard imports
import i18n
import logging
import os
import tempfile
# third party imports
import i18n
import pytest
from chainlib.chain import ChainSpec
from confini import Config
from sqlalchemy import create_engine
# local imports
from cic_ussd.chain import Chain
from cic_ussd.db import dsn_from_config
from cic_ussd.account.chain import Chain
from cic_ussd.encoder import PasswordEncoder
from cic_ussd.files.local_files import create_local_file_data_stores, json_file_parser
from cic_ussd.menu.ussd_menu import UssdMenu
from cic_ussd.metadata import blockchain_address_to_metadata_pointer
from cic_ussd.metadata.signer import Signer
from cic_ussd.metadata.person import PersonMetadata
from cic_ussd.phone_number import E164Format, Support
from cic_ussd.state_machine import UssdStateMachine
from cic_ussd.validator import validate_presence
logg = logging.getLogger()
logg = logging.getLogger(__name__)
fixtures_dir = os.path.dirname(__file__)
root_directory = os.path.dirname(os.path.dirname(fixtures_dir))
@pytest.fixture(scope='session')
def load_config():
config_directory = os.path.join(root_directory, '.config/test')
config = Config(config_dir=config_directory)
config.process(set_as_current=True)
logg.debug('config loaded\n{}'.format(config))
return config
@pytest.fixture(scope='session')
def alembic_config():
migrations_directory = os.path.join(root_directory, 'cic_ussd', 'db', 'migrations', 'default')
@@ -47,22 +33,39 @@ def alembic_config():
}
@pytest.fixture(scope='session')
def alembic_engine(load_config):
data_source_name = dsn_from_config(load_config)
database_engine = create_engine(data_source_name)
return database_engine
@pytest.fixture(scope='function')
def init_state_machine(load_config):
UssdStateMachine.states = json_file_parser(filepath=load_config.get('MACHINE_STATES'))
UssdStateMachine.transitions = json_file_parser(filepath=load_config.get('MACHINE_TRANSITIONS'))
@pytest.fixture(scope='function')
def set_fernet_key(load_config):
PasswordEncoder.set_key(load_config.get('APP_PASSWORD_PEPPER'))
def load_chain_spec(load_config):
chain_spec = ChainSpec(
common_name=load_config.get('CIC_COMMON_NAME'),
engine=load_config.get('CIC_ENGINE'),
network_id=load_config.get('CIC_NETWORK_ID')
)
Chain.spec = chain_spec
@pytest.fixture
def set_locale_files(load_config):
i18n.load_path.append(load_config.get('APP_LOCALE_PATH'))
i18n.set('fallback', load_config.get('APP_LOCALE_FALLBACK'))
@pytest.fixture(scope='session')
def load_config():
config_directory = os.path.join(root_directory, 'config/test')
config = Config(default_dir=config_directory)
config.process()
logg.debug('config loaded\n{}'.format(config))
return config
@pytest.fixture(scope='function')
def load_e164_region(load_config):
E164Format.region = load_config.get('E164_REGION')
@pytest.fixture(scope='session')
def load_support_phone(load_config):
Support.phone_number = load_config.get('OFFICE_SUPPORT_PHONE')
@pytest.fixture
@@ -72,65 +75,12 @@ def load_ussd_menu(load_config):
@pytest.fixture(scope='function')
def load_data_into_state_machine(load_config):
UssdStateMachine.states = json_file_parser(filepath=load_config.get('STATEMACHINE_STATES'))
UssdStateMachine.transitions = json_file_parser(filepath=load_config.get('STATEMACHINE_TRANSITIONS'))
def set_fernet_key(load_config):
PasswordEncoder.set_key(load_config.get('APP_PASSWORD_PEPPER'))
@pytest.fixture(scope='function')
def uwsgi_env():
return {
'REQUEST_METHOD': 'POST',
'REQUEST_URI': '/',
'PATH_INFO': '/',
'QUERY_STRING': '',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SCRIPT_NAME': '',
'SERVER_NAME': 'mango-habanero',
'SERVER_PORT': '9091',
'UWSGI_ROUTER': 'http',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '33515',
'CONTENT_TYPE': 'application/json',
'HTTP_USER_AGENT': 'PostmanRuntime/7.26.8',
'HTTP_ACCEPT': '*/*',
'HTTP_POSTMAN_TOKEN': 'c1f6eb29-8160-497f-a5a1-935d175e2eb7',
'HTTP_HOST': '127.0.0.1:9091',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br',
'HTTP_CONNECTION': 'keep-alive',
'CONTENT_LENGTH': '102',
'wsgi.version': (1, 0),
'wsgi.run_once': False,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.url_scheme': 'http',
'uwsgi.version': b'2.0.19.1',
'uwsgi.node': b'mango-habanero'
}
@pytest.fixture(scope='function')
def setup_metadata_signer(load_config):
temp_dir = tempfile.mkdtemp(dir='/tmp')
logg.debug(f'Created temp dir: {temp_dir}')
Signer.gpg_path = temp_dir
Signer.gpg_passphrase = load_config.get('PGP_PASSPHRASE')
Signer.key_file_path = f"{load_config.get('PGP_KEYS_PATH')}{load_config.get('PGP_PRIVATE_KEYS')}"
@pytest.fixture(scope='function')
def define_metadata_pointer_url(load_config, create_activated_user):
identifier = blockchain_address_to_metadata_pointer(blockchain_address=create_activated_user.blockchain_address)
PersonMetadata.base_url = load_config.get('CIC_META_URL')
person_metadata_client = PersonMetadata(identifier=identifier)
return person_metadata_client.url
@pytest.fixture(scope='function')
def setup_chain_spec(load_config):
chain_spec = ChainSpec(
common_name=load_config.get('CIC_COMMON_NAME'),
engine=load_config.get('CIC_ENGINE'),
network_id=load_config.get('CIC_NETWORK_ID')
)
Chain.spec = chain_spec
@pytest.fixture
def set_locale_files(load_config):
validate_presence(load_config.get('LOCALE_PATH'))
i18n.load_path.append(load_config.get('LOCALE_PATH'))
i18n.set('fallback', load_config.get('LOCALE_FALLBACK'))

View File

@@ -1,4 +1,5 @@
# standard imports
import logging
import os
# third party imports
@@ -8,17 +9,30 @@ from alembic.config import Config as AlembicConfig
# local imports
from cic_ussd.db import dsn_from_config
from cic_ussd.db.models.base import SessionBase
from tests.fixtures.config import root_directory
from cic_ussd.db.models.base import SessionBase, create_engine
from .config import root_directory
logg = logging.getLogger(__name__)
@pytest.fixture(scope='session')
def alembic_engine(load_config):
data_source_name = dsn_from_config(load_config)
return create_engine(data_source_name)
@pytest.fixture(scope='session')
def database_engine(load_config):
data_source_name = dsn_from_config(load_config)
SessionBase.connect(data_source_name)
yield data_source_name
if load_config.get('DATABASE_ENGINE') == 'sqlite':
os.unlink(load_config.get('DATABASE_NAME'))
try:
os.unlink(load_config.get('DATABASE_NAME'))
except FileNotFoundError:
pass
SessionBase.transactional = False
SessionBase.poolable = False
dsn = dsn_from_config(load_config)
SessionBase.connect(dsn, debug=load_config.get('DATABASE_DEBUG') is not None)
return dsn
@pytest.fixture(scope='function')
@@ -27,8 +41,9 @@ def init_database(load_config, database_engine):
migrations_directory = os.path.join(db_directory, 'migrations', load_config.get('DATABASE_ENGINE'))
if not os.path.isdir(migrations_directory):
migrations_directory = os.path.join(db_directory, 'migrations', 'default')
logg.info(f'using migrations directory {migrations_directory}')
SessionBase.session = SessionBase.create_session()
session = SessionBase.create_session()
alembic_config = AlembicConfig(os.path.join(migrations_directory, 'alembic.ini'))
alembic_config.set_main_option('sqlalchemy.url', database_engine)
@@ -37,8 +52,6 @@ def init_database(load_config, database_engine):
alembic.command.downgrade(alembic_config, 'base')
alembic.command.upgrade(alembic_config, 'head')
yield SessionBase.session
SessionBase.session.commit()
SessionBase.session.close()
yield session
session.commit()
session.close()

View File

@@ -0,0 +1,53 @@
# standard imports
import logging
import os
import tempfile
# external imports
import pytest
from chainlib.hash import strip_0x
from cic_types.processor import generate_metadata_pointer
# local imports
from cic_ussd.metadata import Metadata, PersonMetadata, PhonePointerMetadata, PreferencesMetadata
from cic_ussd.metadata.signer import Signer
logg = logging.getLogger(__name__)
@pytest.fixture(scope='function')
def setup_metadata_signer(load_config):
temp_dir = tempfile.mkdtemp(dir='/tmp')
logg.debug(f'Created temp dir: {temp_dir}')
Signer.gpg_path = temp_dir
Signer.gpg_passphrase = load_config.get('PGP_PASSPHRASE')
Signer.key_file_path = os.path.join(load_config.get('PGP_KEYS_PATH'), load_config.get('PGP_PRIVATE_KEYS'))
@pytest.fixture(scope='function')
def setup_metadata_request_handler(load_config):
Metadata.base_url = load_config.get('CIC_META_URL')
@pytest.fixture(scope='function')
def account_phone_pointer(activated_account):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
return generate_metadata_pointer(identifier, ':cic.phone')
@pytest.fixture(scope='function')
def person_metadata_url(activated_account, setup_metadata_request_handler):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
return PersonMetadata(identifier).url
@pytest.fixture(scope='function')
def phone_pointer_url(activated_account, setup_metadata_request_handler):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
return PhonePointerMetadata(identifier).url
@pytest.fixture(scope='function')
def preferences_metadata_url(activated_account, setup_metadata_request_handler):
identifier = bytes.fromhex(strip_0x(activated_account.blockchain_address))
return PreferencesMetadata(identifier).url

View File

@@ -1,95 +0,0 @@
# standard imports
import json
from io import StringIO
# third-party imports
import pytest
# local imports
from cic_ussd.translation import translation_for
from cic_ussd.transactions import truncate
@pytest.fixture(scope='function')
def mock_meta_post_response():
return {
'name': 'cic',
'version': '1',
'ext': {
'network': {
'name': 'pgp',
'version': '2'
},
'engine': {
'name': 'automerge',
'version': '0.14.1'
}
},
'payload': '["~#iL",[["~#iM",["ops",["^0",[["^1",["action","set","obj","00000000-0000-0000-0000-000000000000",'
'"key","id","value","7e2f58335a69ac82f9a965a8fc35403c8585ea601946d858ee97684a285bf857"]],["^1",'
'["action","set","obj","00000000-0000-0000-0000-000000000000","key","timestamp","value",'
'1613487781]], '
'["^1",["action","set","obj","00000000-0000-0000-0000-000000000000","key","data","value",'
'"{\\"foo\\": '
'\\"bar\\", \\"xyzzy\\": 42}"]]]],"actor","2b738a75-2aad-4ac8-ae8d-294a5ea4afad","seq",1,"deps",'
'["^1", '
'[]],"message","Initialization","undoable",false]],["^1",["ops",["^0",[["^1",["action","makeMap",'
'"obj","a921a5ae-0554-497a-ac2e-4e829d8a12b6"]],["^1",["action","set","obj",'
'"a921a5ae-0554-497a-ac2e-4e829d8a12b6","key","digest","value","W10="]],["^1",["action","link",'
'"obj", '
'"00000000-0000-0000-0000-000000000000","key","signature","value",'
'"a921a5ae-0554-497a-ac2e-4e829d8a12b6"]]]],"actor","2b738a75-2aad-4ac8-ae8d-294a5ea4afad","seq",2,'
'"deps",["^1",[]],"message","sign"]]]]',
'digest': 'W10='
}
@pytest.fixture(scope='function')
def mock_meta_get_response():
return {
"foo": "bar",
"xyzzy": 42
}
@pytest.fixture(scope='function')
def mock_notifier_api(mocker):
messages = []
def mock_sms_api(self, message: str, recipient: str):
pass
def mock_send_sms_notification(self, key: str, phone_number: str, preferred_language: str, **kwargs):
message = translation_for(key=key, preferred_language=preferred_language, **kwargs)
messages.append({'message': message, 'recipient': phone_number})
mocker.patch('cic_notify.api.Api.sms', mock_sms_api)
mocker.patch('cic_ussd.notifications.Notifier.send_sms_notification', mock_send_sms_notification)
return messages
@pytest.fixture(scope='function')
def mock_outgoing_transactions(mocker):
transactions = []
def mock_process_outgoing_transfer_transaction(self, amount: int, token_symbol: str = 'SRF'):
transactions.append({
'amount': amount,
'token_symbol': token_symbol
})
mocker.patch(
'cic_ussd.transactions.OutgoingTransactionProcessor.process_outgoing_transfer_transaction',
mock_process_outgoing_transfer_transaction
)
return transactions
@pytest.fixture(scope='function')
def mock_balance(mocker):
mocked_operational_balance = mocker.patch('cic_ussd.accounts.BalanceManager.get_balances')
def _mock_operational_balance(balance: int):
mocked_operational_balance.return_value = truncate(value=balance, decimals=2)
return _mock_operational_balance

View File

View File

@@ -0,0 +1,104 @@
# standard imports
import os
# external imports
import pytest
# local imports
from cic_ussd.translation import translation_for
# test imports
from tests.helpers.accounts import blockchain_address
@pytest.fixture(scope='function')
def mock_account_creation_task_request(mocker, task_uuid):
def mock_request(self):
mocked_task_request = mocker.patch('celery.app.task.Task.request')
mocked_task_request.id = task_uuid
return mocked_task_request
mocker.patch('cic_eth.api.api_task.Api.create_account', mock_request)
@pytest.fixture(scope='function')
def mock_account_creation_task_result(mocker, task_uuid):
def task_result(self):
sync_res = mocker.patch('celery.result.AsyncResult')
sync_res.id = task_uuid
sync_res.get.return_value = blockchain_address()
return sync_res
mocker.patch('cic_eth.api.api_task.Api.create_account', task_result)
@pytest.fixture(scope='function')
def mock_async_balance_api_query(mocker):
query_args = {}
def async_api_query(self, address: str, token_symbol: str):
query_args['address'] = address
query_args['token_symbol'] = token_symbol
mocker.patch('cic_eth.api.api_task.Api.balance', async_api_query)
return query_args
@pytest.fixture(scope='function')
def mock_notifier_api(mocker):
sms = {}
def mock_sms_api(self, message: str, recipient: str):
pass
def send_sms_notification(self, key: str, phone_number: str, preferred_language: str, **kwargs):
message = translation_for(key=key, preferred_language=preferred_language, **kwargs)
sms['message'] = message
sms['recipient'] = phone_number
mocker.patch('cic_notify.api.Api.sms', mock_sms_api)
mocker.patch('cic_ussd.notifications.Notifier.send_sms_notification', send_sms_notification)
return sms
@pytest.fixture(scope='function')
def mock_sync_balance_api_query(balances, mocker, task_uuid):
def sync_api_query(self, address: str, token_symbol: str):
sync_res = mocker.patch('celery.result.AsyncResult')
sync_res.id = task_uuid
sync_res.get.return_value = balances
return sync_res
mocker.patch('cic_eth.api.api_task.Api.balance', sync_api_query)
@pytest.fixture(scope='function')
def mock_sync_default_token_api_query(default_token_data, mocker, task_uuid):
def mock_query(self):
sync_res = mocker.patch('celery.result.AsyncResult')
sync_res.id = task_uuid
sync_res.get.return_value = default_token_data
return sync_res
mocker.patch('cic_eth.api.api_task.Api.default_token', mock_query)
@pytest.fixture(scope='function')
def mock_transaction_list_query(mocker):
query_args = {}
def mock_query(self, address: str, limit: int):
query_args['address'] = address
query_args['limit'] = limit
mocker.patch('cic_eth.api.api_task.Api.list', mock_query)
return query_args
@pytest.fixture(scope='function')
def mock_transfer_api(mocker):
transfer_args = {}
def mock_transfer(self, from_address: str, to_address: str, value: int, token_symbol: str):
transfer_args['from_address'] = from_address
transfer_args['to_address'] = to_address
transfer_args['value'] = value
transfer_args['token_symbol'] = token_symbol
mocker.patch('cic_eth.api.api_task.Api.transfer', mock_transfer)
return transfer_args

View File

@@ -1,11 +0,0 @@
# third party imports
import pytest
# local imports
from cic_ussd.redis import InMemoryStore
@pytest.fixture(scope='function')
def init_redis_cache(redisdb):
InMemoryStore.cache = redisdb
return redisdb

View File

@@ -1,20 +0,0 @@
# third party imports
import pytest
@pytest.fixture(scope='function')
def valid_locked_accounts_env(uwsgi_env):
env = uwsgi_env
env['REQUEST_METHOD'] = 'GET'
env['PATH_INFO'] = '/accounts/locked/10/10'
return env
@pytest.fixture(scope='function')
def get_request_with_params_env(uwsgi_env):
env = uwsgi_env
env['REQUEST_METHOD'] = 'GET'
env['REQUEST_URI'] = '/?phone=0700000000'
return env

View File

@@ -1,19 +1,27 @@
# standard imports
import logging
import os
import pytest
import shutil
import tempfile
# external imports
from celery import uuid
logg = logging.getLogger()
@pytest.fixture(scope='session')
def celery_includes():
return [
'cic_ussd.tasks.ussd',
'cic_ussd.tasks.callback_handler',
'cic_ussd.tasks.metadata',
'cic_ussd.tasks.notifications',
'cic_ussd.tasks.processor',
'cic_ussd.tasks.ussd_session',
'cic_eth.queue.balance',
'cic_notify.tasks.sms',
'cic_ussd.tasks.metadata'
]
@@ -42,3 +50,8 @@ def celery_config():
@pytest.fixture(scope='session')
def celery_enable_logging():
return True
@pytest.fixture(scope='function')
def task_uuid():
return uuid()

View File

@@ -0,0 +1,148 @@
# standard import
import random
# external import
import pytest
# local import
# tests imports
@pytest.fixture(scope='function')
def notification_data(activated_account, cache_person_metadata, cache_preferences, preferences):
return {
'blockchain_address': activated_account.blockchain_address,
'token_symbol': 'GFT',
'token_value': 25000000,
'role': 'sender',
'action_tag': 'Sent',
'direction_tag': 'To',
'metadata_id': activated_account.standard_metadata_id(),
'phone_number': activated_account.phone_number,
'available_balance': 50.0,
'preferred_language': preferences.get('preferred_language')
}
@pytest.fixture(scope='function')
def statement(activated_account):
return [
{
'blockchain_address': activated_account.blockchain_address,
'token_symbol': 'GFT',
'token_value': 25000000,
'role': 'sender',
'action_tag': 'Sent',
'direction_tag': 'To',
'metadata_id': activated_account.standard_metadata_id(),
'phone_number': activated_account.phone_number,
}
]
@pytest.fixture(scope='function')
def transaction_result(activated_account, load_config, valid_recipient):
return {
'hash': '0xb469fb2ebacc9574afb7b51d44e174fba7129fde71bf757fd39784363270832b',
'sender': activated_account.blockchain_address,
'recipient': valid_recipient.blockchain_address,
'source_token_value': 25000000,
'destination_token_value': 25000000,
'source_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'destination_token': '0xa75B519dc9b0A50D267E03D8B6808f85A66932dd',
'source_token_symbol': load_config.get('TEST_TOKEN_SYMBOL'),
'destination_token_symbol': load_config.get('TEST_TOKEN_SYMBOL'),
'source_token_decimals': 6,
'destination_token_decimals': 6,
'chain': 'evm:bloxberg:8996'
}
@pytest.fixture(scope='function')
def transactions_list(activated_account, valid_recipient):
return [
{
'tx_hash': '0x7cdca277861665fa56c4c32930101ff41316c61af3683be12b4879e3d9990125',
'signed_tx': '0xf8a70201837a120094b708175e3f6cd850643aaf7b32212afad50e254980b844a9059cbb000000000000000000000000367cb0f65137b0a845c1db4b7ca47d3def32dde800000000000000000000000000000000000000000000000000000000017d784082466ba030a75acff9081e57e0a9daa6858d7473fc10348bf95a6da4dd1dc6a602883c8da005358742612001ad44fc142c30bcc23b452af48c90f9c6c80433ae2a93b2e96e',
'nonce': 2,
'status': 'SUCCESS',
'status_code': 4104,
'source_token': '0xb708175e3f6Cd850643aAF7B32212AFad50e2549',
'destination_token': '0xb708175e3f6Cd850643aAF7B32212AFad50e2549',
'block_number': 94,
'tx_index': 0,
'sender': activated_account.blockchain_address,
'recipient': valid_recipient.blockchain_address,
'from_value': 25000000,
'to_value': 25000000,
'date_created': '2021-07-14T14:14:58.117017',
'date_updated': '2021-07-14T14:14:58.117017',
'date_checked': '2021-07-14T14:14:58.603124',
'timestamp': 1626272098,
'hash': '0x7cdca277861665fa56c4c32930101ff41316c61af3683be12b4879e3d9990125',
'source_token_symbol': 'GFT',
'source_token_decimals': 6,
'destination_token_symbol': 'GFT',
'destination_token_decimals': 6
},
{
'tx_hash': '0x5bd3b72f07ceb55199e759e8e82006b1c70bd5b87a3d37e3327515ea27872290',
'signed_tx': '0xf88601018323186094103d1ed6e370dba6267045c70d4999384c18a04a80a463e4bff4000000000000000000000000367cb0f65137b0a845c1db4b7ca47d3def32dde882466ca00beb6913cdd0b9b63469fbca53e2fb48dceeedf73d31d54c23c85392f01419a8a02352fff9187ba3dd6409ef6e473369dc4c3459a8baaa9bc1d68a541ca8a8f923',
'nonce': 1,
'status': 'REVERTED',
'status_code': 5128,
'source_token': '0x0000000000000000000000000000000000000000',
'destination_token': '0x0000000000000000000000000000000000000000',
'block_number': 80,
'tx_index': 0,
'sender': '0x367cB0F65137b0A845c1DB4B7Ca47D3DEF32dDe8',
'recipient': '0x103d1ed6e370dBa6267045c70d4999384c18a04A',
'from_value': 0,
'to_value': 0,
'date_created': '2021-07-14T14:13:46.036198',
'date_updated': '2021-07-14T14:13:46.036198',
'date_checked': '2021-07-14T14:13:46.450050',
'timestamp': 1626272026,
'hash': '0x5bd3b72f07ceb55199e759e8e82006b1c70bd5b87a3d37e3327515ea27872290'},
{
'tx_hash': '0x9d586562e1e40ae80fd506161e59825bc316293b5c522b8f243cf6c804c7843b',
'signed_tx': '0xf868800182520894367cb0f65137b0a845c1db4b7ca47d3def32dde887066517289880008082466ca0c75083ea13d4fa9dfd408073cd0a8234199b78e79afe441fb71d7c79aa282ca6a00a7dd29e3ec1102817236d85af365fce7593b337ee609d02efdb86d298cf11ab',
'nonce': 0,
'status': 'SUCCESS',
'status_code': 4104,
'source_token': '0x0000000000000000000000000000000000000000',
'destination_token': '0x0000000000000000000000000000000000000000',
'block_number': 78,
'tx_index': 0,
'sender': '0xb41BfEE260693A473254D62b81aE1ADCC9E51AFb',
'recipient': '0x367cB0F65137b0A845c1DB4B7Ca47D3DEF32dDe8',
'from_value': 1800000000000000,
'to_value': 1800000000000000,
'date_created': '2021-07-14T14:13:35.839638',
'date_updated': '2021-07-14T14:13:35.839638',
'date_checked': '2021-07-14T14:13:36.333426',
'timestamp': 1626272015,
'hash': '0x9d586562e1e40ae80fd506161e59825bc316293b5c522b8f243cf6c804c7843b'
},
{
'tx_hash': '0x32ca3dd3bef06463b452f4d32f5f563d083cb4759219eed90f3d2a9c1791c5fc',
'signed_tx': '0xf88680018323186094103d1ed6e370dba6267045c70d4999384c18a04a80a463e4bff4000000000000000000000000367cb0f65137b0a845c1db4b7ca47d3def32dde882466ca0ab9ec1c6affb80f54bb6c2a25e64f38b3da840404180fb189bd6e191266f3c63a03cc53e59f8528da04aeec36ab8ae099553fca366bd067feffed6362ccb28d8f0',
'nonce': 0,
'status': 'SUCCESS',
'status_code': 4104,
'source_token': '0x0000000000000000000000000000000000000000',
'destination_token': '0x0000000000000000000000000000000000000000',
'block_number': 79,
'tx_index': 0,
'sender': '0x367cB0F65137b0A845c1DB4B7Ca47D3DEF32dDe8',
'recipient': '0x103d1ed6e370dBa6267045c70d4999384c18a04A',
'from_value': 0,
'to_value': 0,
'date_created': '2021-07-14T14:13:35.638355',
'date_updated': '2021-07-14T14:13:35.638355',
'date_checked': '2021-07-14T14:13:40.927113',
'timestamp': 1626272015,
'hash': '0x32ca3dd3bef06463b452f4d32f5f563d083cb4759219eed90f3d2a9c1791c5fc'}
]

View File

@@ -1,120 +0,0 @@
# standard imports
import json
import uuid
from random import randint
# third party imports
import pytest
from cic_types.models.person import generate_metadata_pointer
from faker import Faker
# local imports
from cic_ussd.db.models.account import AccountStatus, Account
from cic_ussd.redis import cache_data
from cic_ussd.metadata import blockchain_address_to_metadata_pointer
fake = Faker()
@pytest.fixture(scope='function')
def create_activated_user(init_database, set_fernet_key):
user = Account(
blockchain_address='0xFD9c5aD15C72C6F60f1a119A608931226674243f',
phone_number='+25498765432'
)
user.preferred_language = 'en'
user.create_password('0000')
user.activate_account()
init_database.add(user)
init_database.commit()
return user
@pytest.fixture(scope='function')
def create_valid_tx_recipient(init_database, set_fernet_key):
user = Account(
blockchain_address='0xd6204101012270Bf2558EDcFEd595938d1847bf0',
phone_number='+25498765432'
)
user.preferred_language = 'en'
user.create_password('0000')
user.activate_account()
init_database.add(user)
init_database.commit()
return user
@pytest.fixture(scope='function')
def create_valid_tx_sender(init_database, set_fernet_key):
user = Account(
blockchain_address='0xd6204101012270Bf2558EDcFEd595938d1847bf1',
phone_number='+25498765433'
)
user.preferred_language = 'en'
user.create_password('0000')
user.activate_account()
init_database.add(user)
init_database.commit()
return user
@pytest.fixture(scope='function')
def create_pending_user(init_database, set_fernet_key):
user = Account(
blockchain_address='0x0ebdea8612c1b05d952c036859266c7f2cfcd6a29842d9c6cce3b9f1ba427588',
phone_number='+25498765432'
)
init_database.add(user)
init_database.commit()
return user
@pytest.fixture(scope='function')
def create_pin_blocked_user(init_database, set_fernet_key):
user = Account(
blockchain_address='0x0ebdea8612c1b05d952c036859266c7f2cfcd6a29842d9c6cce3b9f1ba427588',
phone_number='+25498765432'
)
user.create_password('0000')
user.failed_pin_attempts = 3
user.account_status = 3
init_database.add(user)
init_database.commit()
return user
@pytest.fixture(scope='function')
def create_locked_accounts(init_database, set_fernet_key):
for i in range(20):
blockchain_address = str(uuid.uuid4())
phone_number = fake.phone_number()
pin = f'{randint(1000, 9999)}'
user = Account(phone_number=phone_number, blockchain_address=blockchain_address)
user.create_password(password=pin)
user.failed_pin_attempts = 3
user.account_status = AccountStatus.LOCKED.value
user.session.add(user)
user.session.commit()
@pytest.fixture(scope='function')
def complete_user_metadata(create_activated_user):
return {
"date_registered": create_activated_user.created,
"family_name": "Snow",
"given_name": "Name",
"gender": 'Male',
"location": "Kangemi",
"products": "Mandazi"
}
@pytest.fixture(scope='function')
def cached_user_metadata(create_activated_user, init_redis_cache, person_metadata):
user_metadata = json.dumps(person_metadata)
key = generate_metadata_pointer(
identifier=blockchain_address_to_metadata_pointer(blockchain_address=create_activated_user.blockchain_address),
cic_type=':cic.person'
)
cache_data(key=key, data=user_metadata)

View File

@@ -1,52 +1,69 @@
# standard imports
import json
import os
import random
# third-party imports
# external imports
import pytest
# local imports
from cic_ussd.db.models.ussd_session import UssdSession
from cic_ussd.redis import InMemoryStore
from cic_ussd.session.ussd_session import UssdSession as InMemoryUssdSession
from cic_ussd.session.ussd_session import create_ussd_session
# test imports
from tests.helpers.accounts import phone_number
@pytest.fixture(scope='function')
def ussd_session_data():
def activated_account_ussd_session(load_config, activated_account):
valid_service_codes = load_config.get('USSD_SERVICE_CODE').split(",")
return {
'external_session_id': 'AT974186',
'service_code': '*483*46#',
'msisdn': '+25498765432',
'user_input': '1',
'data': {},
'external_session_id': os.urandom(20).hex(),
'msisdn': activated_account.phone_number,
'service_code': valid_service_codes[0],
'state': 'initial_language_selection',
'session_data': {},
'user_input': '1',
}
@pytest.fixture(scope='function')
def generic_ussd_session(load_config, activated_account):
valid_service_codes = load_config.get('USSD_SERVICE_CODE').split(",")
return {
'data': {},
'service_code': valid_service_codes[0],
'state': 'initial_language_selection',
'user_input': '1',
'version': 2
}
@pytest.fixture(scope='function')
def create_in_redis_ussd_session(ussd_session_data, init_redis_cache):
external_session_id = ussd_session_data.get('external_session_id')
InMemoryUssdSession.redis_cache = InMemoryStore.cache
InMemoryUssdSession.redis_cache.set(external_session_id, json.dumps(ussd_session_data))
return InMemoryUssdSession.redis_cache
def ussd_session_traffic(generic_ussd_session, init_database, persisted_ussd_session):
for _ in range((random.randint(5, 15))):
generic_ussd_session['external_session_id'] = os.urandom(20).hex()
generic_ussd_session['msisdn'] = phone_number()
ussd = UssdSession(**{key: value for key, value in generic_ussd_session.items()})
init_database.add(ussd)
init_database.commit()
@pytest.fixture(scope='function')
def get_in_redis_ussd_session(ussd_session_data, create_in_redis_ussd_session):
external_session_id = ussd_session_data.get('external_session_id')
ussd_session_data = create_in_redis_ussd_session.get(external_session_id)
ussd_session_data = json.loads(ussd_session_data)
# remove version from ussd_session data because the ussd_session object does not expect a version at initialization
del ussd_session_data['version']
ussd_session = InMemoryUssdSession(**{key: value for key, value in ussd_session_data.items()})
ussd_session.version = ussd_session_data.get('version')
return ussd_session
def ussd_session_data(load_config):
return {
'recipient': phone_number()
}
@pytest.fixture(scope='function')
def create_in_db_ussd_session(init_database, ussd_session_data):
ussd_session_data['session_data'] = {}
ussd_session = UssdSession(**{key: value for key, value in ussd_session_data.items()})
init_database.add(ussd_session)
def cached_ussd_session(init_cache, activated_account_ussd_session):
return create_ussd_session(**{key: value for key, value in activated_account_ussd_session.items()})
@pytest.fixture(scope='function')
def persisted_ussd_session(init_cache, init_database, activated_account_ussd_session):
activated_account_ussd_session['version'] = 2
ussd = UssdSession(**{key: value for key, value in activated_account_ussd_session.items()})
init_database.add(ussd)
init_database.commit()
return ussd_session
return ussd

63
apps/cic-ussd/tests/fixtures/util.py vendored Normal file
View File

@@ -0,0 +1,63 @@
# standard imports
# external imports
import pytest
# local imports
@pytest.fixture(scope='function')
def uwsgi_env():
return {
'REQUEST_METHOD': 'POST',
'REQUEST_URI': '/',
'PATH_INFO': '/',
'QUERY_STRING': '',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SCRIPT_NAME': '',
'SERVER_NAME': 'mango-habanero',
'SERVER_PORT': '9091',
'UWSGI_ROUTER': 'http',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '33515',
'CONTENT_TYPE': 'application/json',
'HTTP_USER_AGENT': 'PostmanRuntime/7.26.8',
'HTTP_ACCEPT': '*/*',
'HTTP_POSTMAN_TOKEN': 'c1f6eb29-8160-497f-a5a1-935d175e2eb7',
'HTTP_HOST': '127.0.0.1:9091',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br',
'HTTP_CONNECTION': 'keep-alive',
'CONTENT_LENGTH': '102',
'wsgi.version': (1, 0),
'wsgi.run_once': False,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.url_scheme': 'http',
'uwsgi.version': b'2.0.19.1',
'uwsgi.node': b'mango-habanero'
}
@pytest.fixture(scope='function')
def locked_accounts_env(with_params_env):
with_params_env['PATH_INFO'] = '/accounts/locked/10/10'
return with_params_env
@pytest.fixture(scope='function')
def with_params_env(uwsgi_env):
uwsgi_env['REQUEST_METHOD'] = 'GET'
uwsgi_env['REQUEST_URI'] = '/?phone=0700000000'
return uwsgi_env
@pytest.fixture(scope='function')
def mock_url():
return 'https://testing.io'
@pytest.fixture(scope='function')
def mock_response():
return {
'Looking': 'Good'
}